简体   繁体   English

使用基于 sed/awk 的 linux 替换字符串

[英]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.在 BASH 中的双引号内,否则将发生历史扩展。

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.在这种情况下,我使用:因为 sed 在不同的斜杠之间混淆,并且无法再用一个分隔符来区分,而其中一个是文本的一部分。 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.如果输入文件和输出文件具有相同的名称,请记住输入-new ,因为如果没有它,您的原始文件将被完全清除:这发生在我过去,这根本不是最好的事情。 For example:例如:

<test.txt >test-new.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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