bash sed 返回“sed:命令乱码”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19388443/
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
sed returns "sed: command garbled"
提问by user2877175
I have this data in file.txt:
我在 file.txt 中有这些数据:
1234-abca-dgdsf-kds-2;abc dfsfds 2
123-abcdegfs-sdsd;dsfdsf dfd f
12523-cvjbsvndv-dvd-dvdv;dsfdsfpage
I want to replace the string after "-" and up to ";" with just ";", so that I get:
我想替换“-”之后的字符串,直到“;” 只用“;”,所以我得到:
1234;abc dfsfds 2
123;dsfdsf dfd f
12523;dsfdsfpage
I tried with the command:
我尝试使用以下命令:
sed -e "s/-.*;/;" file.txt
But it gives me the following error:
但它给了我以下错误:
sed command garbled
sed 命令乱码
Why is this happening?
为什么会这样?
采纳答案by iamauser
This should work :
这应该工作:
sed 's/-.*;/;/g' file > newFile
回答by fedorqui 'SO stop harming'
sed
replacement commands are defined as (source):
sed
替换命令定义为(源):
's/REGEXP/REPLACEMENT/[FLAGS]'
(substitute) Match the regular-expression against the content of the pattern space. If found, replace matched string with REPLACEMENT.
's/REGEXP/REPLACEMENT/[FLAGS]'
(替代)将正则表达式与模式空间的内容进行匹配。如果找到,用 REPLACEMENT 替换匹配的字符串。
However, you are saying:
然而,你是说:
sed "s/-.*;/;"
That is:
那是:
sed "s/REGEXP/REPLACEMENT"
And hence missing a "/" at the end of the expression. Just add it to have:
因此在表达式末尾缺少“/”。只需添加它即可:
sed "s/-.*;/;/"
# ^
回答by damienfrancois
You are missing a slash at the end of the sed
command:
您在sed
命令末尾缺少斜线:
Should be "s/-.*;/;/"
应该 "s/-.*;/;/"
回答by Jotne
-.*
here the *
greedy, so this would fail if there are more than one ;
-.*
这里是*
贪婪的,所以如果有多个,这将失败;
echo "12523-cvjbsvndv-dvd-dvdv;dsfdsfpage;test" | sed -e "s/-.*;/;/"
12523;test
Change to -[^;]*
改成 -[^;]*
echo "12523-cvjbsvndv-dvd-dvdv;dsfdsfpage;test" | sed -e "s/-[^;]*;/;/"
12523;dsfdsfpage;test