简体   繁体   English

在Redhat Linux上使用“ sed”查找和替换

[英]Find & Replace on Redhat Linux using “sed”

I have done several searches on this and while the solutions seem obvious, I can't seem to get a definite one for my particular situation. 我对此进行了几次搜索,尽管解决方案看起来很明显,但对于我的特定情况,我似乎找不到确切的解决方案。 I have a file that contains a string "${string}" and I would like to replace it with another string that happens to be a file path "/tmp/myfilepath". 我有一个包含字符串“ $ {string}”的文件,我想用另一个恰好是文件路径“ / tmp / myfilepath”的字符串替换它。

"sed" apparently seems to be the most popular choice to do this in linux. 在Linux中,“ sed”显然是最受欢迎的选择。 I am using the following command: 我正在使用以下命令:

sed -i 's/"${string}"/"/tmp/myfilepath"/g' myFile.txt

I get the error message... 我收到错误消息...

sed: -e expression #1, char 5: unknown option to `s'

I am using the double quotes because it has additional slashes in it. 我使用双引号,因为其中有其他斜杠。 I have tried mix-matching single and double quotes, but nothing seems to work. 我试过混合匹配的单引号和双引号,但似乎没有任何效果。 Any thoughts or solutions? 有什么想法或解决方案吗? Thanks in advance. 提前致谢。

You should escape the backslashes in your substitution string: 您应该在替换字符串中转义反斜杠:

sed -i 's/"${string}"/"\/tmp\/myfilepath"/g' myFile.txt

Or use a different delimiter with the substitution command, such as a colon: 或在替换命令中使用其他定界符,例如冒号:

sed -i 's:"${string}":"/tmp/myfilepath":g' myFile.txt

Use a different delimiter: 使用其他定界符:

sed -i "s|${string}|/tmp/myfilepath|g" myFile.txt

If the string can contain special characters, fix it first. 如果字符串可以包含特殊字符,请首先对其进行修复

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

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