简体   繁体   中英

Using negative numbers with sed

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 eg: -10 ?

[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:

\-[0-9]+

(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:

\-?[0-9]+  

(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 sed does not support extended regular expressions. If they don't work, use these instead:

\-[0-9]\{1,\}
\-\{0,1\}[0-9]\{1,\}

Also, Jonathan's answer also includes this, which will match a leading + too--not requested in the question, but a good touch for sure:

[-+]\{0,1\}[0-9]\{1,\}

这应该工作:

\-?[0-9]+

The regex [0-9] matches any single decimal digit.

To match an optionally signed decimal integer in sed , use:

[-+]\{0,1\}[0-9]\{1,\}

The \\{0,1\\} means match 0 or 1 occurrence of the preceding regex (which is either a - or a + ), followed by \\{1,\\} (one or more) digits [0-9] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM