threaz
threaz

Reputation: 403

Sed and dollar sign

"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?

Upvotes: 1

Views: 7474

Answers (3)

anubhava
anubhava

Reputation: 785266

$ 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

Upvotes: 7

200_success
200_success

Reputation: 7582

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

Upvotes: 5

Avinash Raj
Avinash Raj

Reputation: 174706

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.

Upvotes: 4

Related Questions