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 ,
.
$s/$/;/
= at the last line, replace the end of the line with;
$q
= at the last line, quits/$/,/
= 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
精彩评论