简体   繁体   中英

Replacing string in linux using sed/awk based

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM