Some SED Commands

Valic —  November 30, 2010 — Leave a comment

Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed’s ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

Here are some SED commands used by everyone:

1) Print all the lines between 10 and 20 of a file

sed -n ’10,20p’ <filename>

Similarly, if you want to print from 10 to the end of line you can use: sed -n ’10,$p’ filename

This is especially useful if you are dealing with a large file. Sometimes you just want to extract a sample without opening the entire file.

2) Check your unread Gmail from the command line

curl -u username –silent “” | perl -ne ‘print “\t” if /<name>/; print “$2\n” if /<(title|name)>(.*)<\/\1>/;’

Checks the Gmail ATOM feed for your account, parses it and outputs a list of unread messages.

3) To print a specific line from a file

sed -n 5p <file>

You can get one specific line during any procedure. Very interesting to be used when you know what line you want.

4) Remove a line in a text file. Useful to fix “ssh host key change” warnings

sed -i 8d ~/.ssh/known_hosts

5) Recursive search and replace old with new string, inside files

grep -rl oldstring . |xargs sed -i -e ‘s/oldstring/newstring/’

recursively traverse the directory structure from . down, look for string “oldstring” in all files, and replace it with “newstring”, wherever found


grep -rl oldstring . |xargs perl -pi~ -e 's/oldstring/newstring'


Posts Twitter Facebook

Editor in Chief at Debian-Tutorials, Linux enthusiast.

No Comments

Be the first to start the conversation.

Leave a Reply