Sed and dollar sign

时光毁灭记忆、已成空白 提交于 2019-12-11 12:05:15

问题


"The Unix Programming Environment" states that '$' used in regular expression in sed means end-of-the line which is fine for me, because

cat file | sed 's/$/\n/'

is interpretted as "add newline at the end of each line".

The question arises, when I try to use the command:

cat file | sed '$d'

Shouldn't this line remove each line instead of the last one? In this context, dollar sign means end of the LAST line. What am I getting wrong?


回答1:


Note that regex in sed must be inside the delimiters(;,:, ~, etc) other than quotes.

/regex/

ex:

sed '/foo/s/bar/bux/g' file

or

~regex~

ex:

sed 's~dd~s~' file

but not 'regex'. So $ in '$d' won't be considered as regex by sed. '$d' acts like an address which points out the last line.




回答2:


In the second usage, there is no regular expression. The $ there is an address, meaning the last line.




回答3:


$ is treated as regex anchor when used in pattern in s command e.g.

s/$/\n

However in $d, $ is not a regex anchor, it is address notation that means the last line of the input, which is deleted using the d command.

Also note that cat is unnecessary in your last command. It can be used as:

sed '$d' file


来源:https://stackoverflow.com/questions/31370580/sed-and-dollar-sign

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!