bash 在使用 sed 时寻找匹配的“'”时出现意外的 EOF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24673698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unexpected EOF while looking for matching `'' while using sed
提问by Bharat
Yes this question has been asked many times, and in the answer it is said to us \
escape character before the single quote.
是的,这个问题已经被问过很多次了,在答案中,它告诉我们\
在单引号之前转义字符。
In the below code it isn't working:
在下面的代码中它不起作用:
LIST="(96634,IV14075295,TR14075685')"
LIST=`echo $LIST | sed 's/,/AAA/g' `
echo $LIST # Output: (96634AAAIV14075295AAATR14075685')
# Now i want to quote the list elements
LIST=`echo $LIST | sed 's/,/\',\'/g' ` # Giving error
# exit 0
Error :
错误 :
line 7: unexpected EOF while looking for matching `''
line 8: syntax error: unexpected end of file
回答by Avinash Raj
Instead of single quotes, use double quotes in sed command, and also remove the space before last backtick. If there is single quote present in the sed pattern then use an alternative enclosing quotes(ie, double quotes),
在 sed 命令中使用双引号代替单引号,并删除最后一个反引号之前的空格。如果 sed 模式中存在单引号,则使用替代的封闭引号(即双引号),
sed "s/,/\',\'/g"
And the line would be,
这条线是,
LIST=$(echo $LIST | sed "s/,/\',\'/g")
Don't use backticks inside the sripts instead of bacticks, use $()
不要在 sripts 内使用反引号而不是 bacticks,使用 $()
回答by Jotne
You can use awk
您可以使用 awk
echo $LIST
(96634,IV14075295,TR14075685')
LIST=$(awk '{gsub(/,/,q"&"q)};gsub(/\(/,"&"q)1' q="'" <<< $LIST)
echo $LIST
('96634','IV14075295','TR14075685')
To prevent problems with the single quote, I just set it to an awk
variable.
为了防止单引号出现问题,我只是将它设置为一个awk
变量。
回答by Deleted User
consider
考虑
LIST="$(sed "s/,/\',\'/g" <<< "$LIST")"
but first and last elements probably won't get quoted completely, because of missing leading and trailing comma
但是第一个和最后一个元素可能不会被完全引用,因为缺少前导和尾随逗号
btw, you don't need to subshell to sed - string matching and substitution is entirely within the capabilities of bash:
顺便说一句,您不需要将子shell转为 sed - 字符串匹配和替换完全在 bash 的能力范围内:
LIST="${LIST//,/\',\'}"