简体   繁体   English

sed命令产生意外结果

[英]Sed command giving unexpected result

Below is the shell script I am trying to find the meaning. 下面是我试图找到含义的shell脚本。

sed 's/19984 $/98400 /' | sed 's/19992 $/99200 /'

I expect 19984 $ will get replaced with 98400 and this string will be passed to next sed command which replace 19992 $ with 99200 . 我希望将19984 $替换为98400,并将此字符串传递给下一个sed命令,该命令将19992 $替换为99200。

But when I executed the script below with sample input 但是当我使用示例输入执行以下脚本时

echo "19984 $ need to be  replaced with 98400  "| sed 's/19984 $/98400 /' | sed 's/19992 $/99200 /'

I get the same string 我得到相同的字符串

"19984 $ need to be  replaced with 98400"

I hope something I am missing here. 我希望我在这里想念的东西。 Please help me. 请帮我。 I am new to shell scripts. 我是Shell脚本的新手。 Thanks in advance! 提前致谢!

For sed, $ is a reserved character to you have to escape it ( \\$ ) to be parsed properly: 对于sed, $是保留字符,您必须对其进行转义( \\$ )才能正确解析:

$ echo "19984 $ need to be  replaced with 98400  "| sed 's/19984 \$/98400 /' 
98400  need to be  replaced with 98400

All together: 全部一起:

$ echo "19984 $ need to be  replaced with 98400  "| sed 's/19984 \$/98400 /' | sed 's/19992 \$/99200 /'
98400  need to be  replaced with 98400

So you need to keep it like it is. 因此,您需要保持原样。

$ can mean a lot of things: $可能意味着很多事情:
- a normal character. -正常角色。
- end of line. - 行结束。
- name of a variable. -变量名。

The way you got the code it means the second case: end of line: 获得代码的方式意味着第二种情况:行尾:

$ echo "19984 " | sed 's/19984 $/98400 /'
98400
$ echo "19984 something" | sed 's/19984 $/98400 /'
19984 something

so sed will match just the cases in which the line ends with 19984 . 所以sed将只匹配行以19984结尾的情况。 Otherwise it won't match. 否则,它将不匹配。

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

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