开发者

In a sed transformation, how to apply a slightly different pattern just for the last line?

How can I turn this:

aaa
bbb
ccc

into this:

aaa,
bbb,
ccc

using sed?

Note how all lines end a comma, except the last one.

In my real problem I a开发者_如何学Clso do some regex substitutions on the lines. Is there a solution that doesn't duplicate them?


You could use:

sed '$q;s/$/,/'

If you want to apply a different substitution on the last line, you can still use the $ address:

sed '$s/$/;/;$q;s/$/,/'

The above will replace the end of the line with ; if it's the last line, otherwise it will use ,.

  1. $s/$/;/ = at the last line, replace the end of the line with ;
  2. $q = at the last line, quit
  3. s/$/,/ = replace the end of the line with ,

The last s command will run for each line, but not for the last line in which the q command at 2. tells it to quit.


See:

  • Restricting to a line number
  • Ranges by line number
  • The q or quit command
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜