英文:
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
以下是已经翻译好的部分:
我将展示不带-i
的sed
命令。当它按照你的要求工作时,可以添加-i
。
当你不确定有多少引号时,你可以尝试
sed 's/echo [^[:alnum:]]*xxx.yyy[^[:alnum:]]/# &/' file.txt
或者当一行同时包含echo
和xxx.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论