Tibor's Musings


Sed, the stream editor, is a useful tool in one's command-line-fu. Here are some nifty one-liners.

Replace stuff in a file:

$ sed -i 's/oldstring/newstring/g' filename

Replace stuff in many files:

$ find modules -name "*.py" -exec sed -i 's,CFG_SOME_VARIABLE,CFG_OTHER_VARIABLE,g' {} \;

Print line number 123 and quit:

$ sed -n '123{p;q}' filename

Comment out line number 123:

$ sed -i '123s/\(.*\)/#\1/' filename

Delete line number 123:

$ sed -i 123d ~/.ssh/known_hosts

Print from line 1 until regexp:

$ sed -n '1,/regex/p' filename

Print from regexp until end of file:

$ sed -n '/regex/,$p' filename