简体   繁体   English

sed返回“ sed:命令乱码”

[英]sed returns “sed: command garbled”

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? 为什么会这样呢?

sed replacement commands are defined as ( source ): sed替换命令定义为( source ):

 's/REGEXP/REPLACEMENT/[FLAGS]' 

(substitute) Match the regular-expression against the content of the pattern space. (替代)将正则表达式与模式空间的内容匹配。 If found, replace matched string with REPLACEMENT. 如果找到,则用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/-.*;/;/"
#            ^

You are missing a slash at the end of the sed command: sed命令末尾缺少斜杠:

Should be "s/-.*;/;/" 应为"s/-.*;/;/"

-.* 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

这应该工作:

sed 's/-.*;/;/g' file > newFile

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

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