sed wildcards for any number
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.txtBefore 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 ItemI'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.txtBut it is more common to use "*":
sed 's/samples : [0-9]* failing samples : [0-9]*/OK/g' ./sedTest.txtEg. 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.txtDepending 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.