开发者

UNIX sed command help

开发者 https://www.devze.com 2023-03-15 19:09 出处:网络
sed -n \'$\'!p abc.txt | tail +2 > def.txt I have the above mentioned sed command in my code - I am unable to figure out what it does -I am going through sed tutorials to find it out but am not a
    sed -n '$'!p abc.txt | tail +2 > def.txt

I have the above mentioned sed command in my code - I am unable to figure out what it does -I am going through sed tutorials to find it out but am not able to 开发者_Go百科- Can some one please help me in figuring out what it does - Thanks


Taking this in stages:

sed -n abc.txt    

"Run abc.txt through sed, but don't print anything out."

sed -n '$!p' abc.txt

(Note that I've corrected what I think was a misplaced quote mark.)

"Run abc.txt through sed; if a line isn't the last line, print it (i.e. print all but the last line)."

I guess you know the rest, but note that tail +2 is obsolete syntax-- tail -n 2 would be better.

EDIT:

To remove the last two lines, try

sed 'N;$d'

or if that doesn't work, crude but effective:

sed '$d' | sed '$d'


As far as the sed command '$'!p is concerned:

  • the $ matches only the last line of the input file.
  • the ! negates the sense of the match (so that it matches all but the last line).
  • the p prints out whatever was matched.

So basically this prints all but the last line of the file.

The -n option stops sed from performing its default action (to print the pattern space) - without that, you'd get one copy of the last line and two copies of all the other lines.

The quotes around $ are to stop the shell from trying to interpret it as a shell variable - I would have quoted the lot myself ('$!p') but that's a style issue, at least on bash. Other shells like csh (which uses ! for command history retrieval) may not be so forgiving.

0

精彩评论

暂无评论...
验证码 换一张
取 消