Replacing string in linux using sed/awk based

45,597

Solution 1

You cannot use ! inside a double quotes in BASH otherwise history expansion will take place.

You can just do:

original_str='/usr/bin/env bash'
replace_str='/bin/bash'

sed "s~$original_str~$replace_str~" file
#!/bin/bash

Solution 2

Using escape characters :

    $ cat z.sh
    #!/usr/bin/env bash

    $ sed -i "s/\/usr\/bin\/env bash/\/bin\/bash/g" z.sh

    $ cat z.sh
    #!/bin/bash

Solution 3

Try this out in the terminal:

echo "#!/usr/bin/env bash" | sed 's:#!/usr/bin/env bash:#!/bin/bash:g'

In this cases I use : because sed gets confused between the different slashes and it isn't able to tell anymore with one separates and wich one is part of the text. Plus it looks really clean. The cool thing is that you can use every symbol you want as a separator. For example a semicolon ; or the pipe symbol | . By using the escape character \ I think that the code would look too messy and wouldn't be very readable, considering the fact that you have to put it before every forward slash in the command.

The command above will just print out the replaced line, but if you want to modify the file, than you need to specify the input and output file, like this:

sed 's:#!/usr/bin/env bash:#!/bin/bash:g' <inputfile >outputfile-new

Remember to put that -new if the inputfile and the output file have the same name, because without it your original one will be cleared completely: this happend me in the past, and it's not the best thing at all. For example:

<test.txt >test-new.txt

Share:
45,597
Subham Tripathi
Author by

Subham Tripathi

Frontend dev at Expedia #SOreadytohelp

Updated on June 26, 2020

Comments

  • Subham Tripathi
    Subham Tripathi almost 4 years

    i want to replace this

    #!/usr/bin/env bash
    

    with this

       #!/bin/bash
    

    i have tried two approaches

    Approach 1

    original_str="#!/usr/bin/env bash"
    replace_str="#!/bin/bash"
    
    sed s~${original_str}~${replace_str}~ filename
    

    Approach 2

    line=`grep -n "/usr/bin" filename`
    awk NR==${line} {sub("#!/usr/bin/env bash"," #!/bin/bash")}
    

    But both of them are not working.