Linux + C – Brief Overview of Sed

via Fort Collins Program

Sed is a powerful editing tool, but difficult for most modern computer users to grasp. We’ll cover some of the basics here so that you can understand it when you see it in a script.

Key Features and Uses of Sed

The sed tool is the most powerful stream editor on the market today. Imagine an assembly line where the tool watches carefully for a pattern of symbols, then performs some operation on those symbols before restarting the line.

The key feature of sed is the replacement tool. When the program sees a regular expression it’s been trained to recognize, it will replace that pattern with some other regular expression. For example, we could find all instances of the word “panda” and replace them with “pandas are awesome” with a very simple script:

sed ‘s_panda_pandas are awesome_’

The other key to sed is a complete understanding of regex. All strings we use for the find and the replace operations are regular expressions, and this extends the functionality of sed a hundredfold.

We primarily employ sed for simple find-and-replace operations. I myself have a script I use to remove unnecessary whitespace (tabs and spaces) from my source code files. It runs on all my files in milliseconds, and the result is 100% reliable.

Some Notes

The format for a replacement in sed is as follows:


We don’t have to use / characters for the delimiter, but this is the usual standard. Above, I used the underscore (_) character as a delimiter because it was easier to read. Use whatever delimiter you can to simplify your regular expressions.

By default, sed will print the output stream to the terminal. We can use file redirection to pipe the output to a new file:

sed ‘s_OLD_NEW_’ old_file > new_file

We can also make sed write back to the original file with the -i (in-place) flag.

sed -i ‘s_OLD_NEW_’ file_name

Personally, I don’t employ most of sed’s features, as in those cases where those features have value, I generally employ AWK. However, it is excellent for a few tasks, and it may appear in any number of useful scripts.

For a much deeper explanation of sed, check out the Grymoire.


Facebook Auto Publish Powered By :