Replacing string in linux using sed/awk based

血红的双手。 提交于 2021-02-04 18:16:13

问题


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.


回答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



回答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



回答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



来源:https://stackoverflow.com/questions/31781256/replacing-string-in-linux-using-sed-awk-based

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!