When using sed, I can use [0-9] to match any number. However, this seems to only look for positive numbers. How can I have it also look for numbers beginning with -, for e.g.: -10?
When using sed , I can use [0-9] to match any number. However, this
Share
[0-9]does not match the numbers 0 through 9. It matches the characters 0,1,2,3,4,5,6,7,8, and 9.To have it require that a
-character precede it, just put it in there, escaped with a backslash so it doesn’t have its usual special meaning in a regexp. So\-[1-9]will match the strings -1, -2, etc. up to -9.If you want it to match any negative number, use:
(The
+means “one or more occurrences of the previous thing” so in this case “one or more digits”.)If you want it to match any negative or positive number, use:
(The
?means “one or zero occurrences of the previous thing” so here it means “a – or nothing”.)UPDATE
@Jonathan Leffler points out that the above will not work if your version of
seddoes not support extended regular expressions. If they don’t work, use these instead:Also, Jonathan’s answer also includes this, which will match a leading
+too–not requested in the question, but a good touch for sure: