A bit of sed unveiled

Posted on October 31, 2009

Some days ago I've discovered a useful usage of sed I did not know about: one can specify line ranges in the expression, to target only certain parts of the stream to edit.
This is achieved with the following:

sed '1,4 s/s/S/' <test 
...it substitutes all occurrencies of s with S in the first four lines, an important thing to remark is that lines counting starts at 1.

By the way:

sed '$ ! s/$/,/' <test
was the reason I started looking at this functionality of sed.
That script does a pretty common task, it adds a comma at the end of all lines, except the last one: the $ means the last line (this logic is also found in other UNIX scripts), and the ! is a negation (the script could have been written with no space between ! and $); this is a task I've encountered lots of times, from today on it will be easier.

Go here for more information, the #1 result on google when you search for sed.

Browse the archive

blog comments powered by Disqus