1

Below is the shell script I am trying to find the meaning.

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 .

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. Thanks in advance!

4

1 回答 1

1

对于 sed,$是一个保留字符,您必须对其进行转义 ( \$) 才能正确解析:

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

全部一起:

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

所以你需要保持原样。

$可能意味着很多事情:
- 一个正常的角色。
- 行结束。
- 变量的名称。

您获取代码的方式意味着第二种情况:行尾:

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

所以 sed 将只匹配该行以 . 结尾的情况19984。否则将不匹配。

于 2013-05-10T09:29:57.380 回答