4

I have a file with lines similar to the below:

0
0.1
0.0002
0
0.30

I want to replace the lines with a single 0 to something else like 0.0001. For the lines with a decimal and digits after, I don't want to alter them.

I've tried the below variations of sed, but it either does nothing, or it changes all the zeros, even ones after the decimals:

sed 's/0/x/g' file
sed 's/^0/x/g' file
sed 's/0^/x/g' file
sed 's/^0^/x/g' file
sed 's/"0"/x/g' file
sed 's/[0]/x/g' file

It seems sed cannot handle a single 0 character. Also, I do not have the replace command on my system. What else can I do?

2 Answers 2

19

To replace a single 0 on a line:

sed 's/^0$/x/'

^ matches the beginning of the line

$ matches the end of a line

So the above command matches the beginning of a line, followed by 0, followed by the end of the line.

5
  • 8
    No need for g modifier..
    – heemayl
    Aug 21, 2015 at 20:57
  • @heemayl if there are multiple lines with just 0 on the surely you would need the g modifier?
    – forquare
    Aug 21, 2015 at 20:58
  • 11
    The whole sed command applies to every line of the file. The g modifier means to replace multiple patterns in the line.
    – chaos
    Aug 21, 2015 at 21:01
  • Ah ha yes. I've been playing with lots of files with long wrapped lines recently!
    – forquare
    Aug 21, 2015 at 22:23
  • @forquare No, g moidifier is needed as g is onlyt need for multiple updates per line. multiple lines are automatically supported.
    – Jasen
    Aug 22, 2015 at 7:35
4

Using Awk:

awk '{gsub(/^0$/,0.0001)};1' file 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .