搜索和替换在包含空格和特殊字符的字符串中在sed中不起作用。

huangapple go评论60阅读模式
英文:

Search and replace not working in sed for string containing space and special character

问题

我要在Linux中的file.txt文件中,将包含字符串echo '"xxx.yyy"的行前缀添加"# "(井号+空格)。

输出应如下所示:

# echo '"xxx.yyy"

我尝试了以下命令:

find file.txt -type f -exec sed -i 's|"echo '"xxx.yyy""|"# echo '"xxx.yyy""|g' {} \;

但我遇到了错误:

sed: -e expression #1, char 23: unterminated `s' command

我应该在这里转义哪个字符?
我在这里做错了什么?

英文:

I want to prefix the line containing the string echo '"xxx.yyy" with "# " (hash+space) in file.txt using sed in Linux.

Output should look like this:

# echo '"xxx.yyy"

I tried this:

find file.txt -type f -exec sed -i 's|"echo '"xxx.yyy""|"# echo '"xxx.yyy""|g' {} \;

But I am getting the error:

sed: -e expression #1, char 23: unterminated `s' command

Should I escape any character here?
What am I doing wrong here?

答案1

得分: 1

你搜索和替换中的单引号导致了错误,因为sed没有看到完整的命令,s选项未终止。

要修复它,你可以尝试以下的sed命令:

sed -i 's|"echo '"'\"'"'"'"xxx.yyy"|"# echo '"'\"'"'"'"xxx.yyy"'"|g' file.txt
英文:

Your single quotes in the search and replacement are causing the error that the s option is unterminated as sed does not see the complete command.

To fix it, you can try this sed

sed -i 's|"echo '"'"'"xxx.yyy"|"# echo '"'"'"xxx.yyy""|g' file.txt

答案2

得分: 1

以下是已经翻译好的部分:

我将展示不带-ised命令。当它按照你的要求工作时,可以添加-i
当你不确定有多少引号时,你可以尝试

sed 's/echo [^[:alnum:]]*xxx.yyy[^[:alnum:]]/# &/' file.txt

或者当一行同时包含echoxxx.yyy时:

sed 's/echo.*xxx.yyy/# &/' file.txt

在这两个命令中,&代表被匹配的部分。

英文:

I will show the sed commands without -i. Add -i when it works like you want.
When you are not sure how much quotes you have, you can try

sed 's/echo [^[:alnum:]]*xxx.yyy[^[:alnum:]]/# &/' file.txt

or when you are already happy when a line has both echo and xxx.yyy:

sed 's/echo.*xxx.yyy/# &/' file.txt

In both commands, the & stands for the part that is matched.

huangapple
  • 本文由 发表于 2023年2月13日 23:35:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定