M HYPE SPLASH
// news

sed wildcards for any number

By John Peck

I'm trying to replace the string "samples : [any number] failing samples : [any number] with the string 'OK' using sed.

This works with single digits. However, I need an option for any number:

sed 's/samples : [0-9] failing samples : [0-9]/OK/g' ./sedTest.txt

Before Data:

10,foo,bar,samples : 9 failing samples : 7,bar,next Item
10,foo,bar,samples : 99 failing samples : 55,bar,next Item
10,foo,bar,samples : 9229 failing samples : 5225,bar,next Item

I'm trying to achieve this..

10,foo,bar,OK,bar,next Item
10,foo,bar,OK,bar,next Item
10,foo,bar,OK,bar,next Item
1

2 Answers

As suggested by Thor, you can use "\+" to greedily swallow all occurrences:

sed 's/samples : [0-9]\+ failing samples : [0-9]\+/OK/g' ./sedTest.txt

But it is more common to use "*":

sed 's/samples : [0-9]* failing samples : [0-9]*/OK/g' ./sedTest.txt

Eg. for the following output:

cat sedTest.txt; echo "Replace numbers..."; sed 's/samples : [0-9]* failing samples : [0-9]*/OK/g' ./sedTest.txt
10,foo,bar,samples : 9 failing samples : 7,bar,next Item
10,foo,bar,samples : 99 failing samples : 55,bar,next Item
10,foo,bar,samples : 9229 failing samples : 5225,bar,next Item
Replace numbers...
10,foo,bar,OK,bar,next Item
10,foo,bar,OK,bar,next Item
10,foo,bar,OK,bar,next Item

As you have noticed [0-9] will only match a single digit. To match more digits, it is necessary to add a quantifier. Since you want "one or more" digits, simply add a + character after the bracket. It will greedily match all characters inside the brackets (in this case, any digits).

sed 's/samples : [0-9]+ failing samples : [0-9]+/OK/g' ./sedTest.txt

Depending on which system you are using, it is possible you need to run sed with either the -r flag (linux) or -E flag (mac). This is to allow for modern regex symbols like +.

Alternatively, instead of using +, use *. This will match "zero or more" instead of "one or more" occurrences. The advantage here is that no flag is required.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy