Find the answer to your Linux question:
Results 1 to 8 of 8
Hi Guys, I have a document, which contains a series of numbers such as: 0 21 551 1 1 2 1 1 5 0 Now, i would like to find ...
  1. #1
    Just Joined!
    Join Date
    May 2008
    Posts
    18

    Question Replace command

    Hi Guys,

    I have a document, which contains a series of numbers such as:

    0
    21
    551
    1
    1
    2
    1
    1
    5
    0

    Now, i would like to find a method of parsing the entire document, and replacing any 0s with 1s, therefore the example above would become:

    1
    21
    551
    1
    1
    2
    1
    1
    5
    1

    Any idea of a command to achieve this?

    Thanks!

  2. #2
    Linux User dxqcanada's Avatar
    Join Date
    Sep 2006
    Location
    Canada
    Posts
    259
    Read up on "sed"



    Men occasionally stumble over the truth,
    but most of them pick themselves up
    and hurry off as if nothing had happened.

    Winston Churchill


    ... then the Unix-Gods created "man" ...

  3. #3
    Just Joined!
    Join Date
    May 2008
    Posts
    18
    Thanks... that did the trick:

    sed 's/string1/string2/g'

    Cheerz!

  4. #4
    Just Joined!
    Join Date
    May 2008
    Posts
    18
    Hi once again, hit a bump here...

    If you run the following:

    sed s/0/1/g yourfile > newfile

    If the number has a 10, this will change to 11... :S

    I need to change 0 to 1, only if it is a whole 0 not 10, 100, 101 etc....

    I tried sed s/"0"/1/g, however no luck...

    Is there any way around this???

    thanks!

  5. #5
    Just Joined!
    Join Date
    May 2008
    Posts
    2

    Cool the same problem

    ~~~spot closely...

  6. #6
    Just Joined!
    Join Date
    May 2008
    Posts
    18
    You'll have to put the sed argument in double quotes or it will interpret the $ as the start of a variable:

    sed -e "s/^0$/1/"

    However, for some strange reason, it doesn't work in a script.... only when executed directly...

    Can you check it out and let me know if you get the same results??

    Thanks!

  7. #7
    Linux User
    Join Date
    Jun 2007
    Posts
    318
    Actually you have to use single quotes otherwise the $ will be interpeted. Although the way it's used in the sed command in this case it doesn't seem to matter. I tried it in a script and it worked for me.

    Code:
    #!/bin/bash -vx
    
    echo "0"|sed -e "s/^0$/1/"
    + echo 0
    + sed -e 's/^0$/1/'
    1
    exit
    + exit

  8. #8
    Just Joined!
    Join Date
    May 2008
    Posts
    18
    Thanks m8!! That did it!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...