简体   繁体   中英

Sed command giving unexpected result

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!

For sed, $ is a reserved character to you have to escape it ( \\$ ) to be parsed properly:

$ 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 . Otherwise it won't match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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