Regex not working with sed

I have this text in a file

"0000000441244" "0000000127769" 

I want to replace all zeros with "L"

I try to do this and nothing gets chnaged

sed -e 's/0+/L/g' regex.txt

sed -e 's/(0+)/L/g' regex.txt

I want to know where I'm wrong

+4
source share
5 answers

A Posix compatible version should use 00* instead of 0+ :

 sed -e 's/00*/L/g' regex.txt 

As an extra note, you only need the g flag if you want to convert "000000012700009" or even "000000012709" to "L127L9" . Otherwise * in 's/00*/L/' will include all zeros at the beginning anyway.

+7
source

On Linux (GNU sed version), both sed -e 's/0\+/L/g' regex.txt and sed -r 's/0+/L/g' regex.txt but if you use Mac (BSD version of sed), none of them work, you should use this instead: sed -E 's/0+/L/g' regex.txt .

In fact, the latter also works on Linux, so it is more portable. For this particular problem, @perreal's suggestion is also portable. But when you need a + or other metacharacter in regular expression, you better know how to get around it.

+2
source

try it

 sed -e 's/0\+/L/g' regex.txt 
+1
source

If you use any flavor of Unix other than GNU, you can either install GNU sed yourself, or simply switch to awk or ruby or perl .

For instance:

 ruby -e 'ARGF.each{|l|puts l.gsub(/0+/, "L")}' regex.txt 

Using awk:

 awk '{gsub("0+", "L"); print $0}' regex.txt 

Extended regular expressions are available on Mac OS / X through -E rather than -E .

In the BSD General Command Guide:

 -E Interpret regular expressions as extended (modern) regular expressions rather than basic regular expressions (BRE's). The re_format(7) manual page fully describes both formats. 
0
source

This may work for you (GNU sed):

 sed 'y/0/L/' file 
0
source

All Articles