Sed, the amazing command line text stream editor, is a staple in my daily life. I use it for any text replacement, especially if the text replacement needs to be done on all files in a directory. Unfortunately, sometimes I still need reminders on how to unleash its awesome power.
Delete a range of lines:
sed -i .bak '25,59d' *.html
This will delete lines 26 through 59 of every .html file in a directory. What happens if you leave off the -i .bak part? It writes the file to stdout, not to the files and you get a screen full of text. Probably not what we’re looking for. By the way, .bak is arbitrary; use whatever you like for your backup extension.
The mighty &:
sed -i .bak 's/this.blur()/&;/g' *.html
This will append a semicolon to the text “this.blur()” so you end up with “this.blur();”. Yay for the &!
Replace a space with a tab!
sed -i 's/ /[--TAB--]/g' file.txt
In place of --TAB-- , provide the keyboard command CTRL + V followed by the TAB key. This command will replace 3 spaces with a tab in the file file.txt.
(source: http://www.atoztoa.com/2008/12/replace-tab-using-sed.html)
NB: I use bash as my shell. The above command should work across the many different shells, but I’ve not tested it in anything other than bash.
I seriously love this sed one liner. Seriously love it. Once, I had the thrilling task of extracting tables from a pdf, so that the tables could be recreated as a spreadsheet. Replacing spaces with tabs ruled the day, and the extracted data was easily imported into the spreadsheet. But the thing to take away from this is that if your sed won’t accept \t, it is still possible to match on a tab!