Master the Linux ‘sed’ Command: A Comprehensive Guide

Peter Hou
2 min readMay 21, 2023

--

This article provides a comprehensive guide for beginners on the sed command in Linux, covering its history, use cases, and several handy tips and tricks. By mastering sed, you can handle text processing tasks with great efficiency, making it a valuable skill for anyone working with Linux.

Instructions

This article aims to provide a comprehensive guide for beginners on how to use the sed (stream editor) command in Linux. It covers the command's history, usage, parameters, common use cases, and tips and tricks.

History

The sed command was developed during the early days of UNIX and has been a part of Linux since its inception. It is widely used for text manipulation and is known for its efficiency and speed.

When and why to use it

sed is used when you need to perform text transformations efficiently on a file or stream. Its power lies in its ability to handle large files and its use of regular expressions for pattern matching and substitution, making it an essential tool for scripting and data wrangling.

How to use it

The basic syntax of the sed command is sed 'command' file_name.

$ echo "Hello World" | sed 's/World/example/'
Hello example

The commonly used parameters

  • -n suppresses the automatic printing of the pattern buffer.
$ echo "Hello World" | sed -n 's/World/example/p'
Hello example
  • -i edits files in-place (makes backup if an extension is supplied).
$ echo "Hello World" > temp.txt
$ sed -i 's/World/example/' temp.txt
$ cat temp.txt
Hello example

Other supported parameters

  • -e allows multiple editing commands.
  • -f allows you to specify a file that contains sed commands.
  • -r uses extended regular expressions.
  • -u makes the buffer unbuffered.

Most common use cases

A common use case for sed is to replace text in a file.

$ echo "Hello World" > temp.txt
$ sed -i 's/World/example/' temp.txt
$ cat temp.txt
Hello example

The tricky skills

sed can perform complex text transformations with a single line of command by chaining multiple commands.

$ echo "Hello World" | sed 's/Hello/Hi/; s/World/example/'
Hi example

What needs to be noted

When using the -i option, be aware that it can alter files irreversibly. Always ensure that you have a backup, especially when working with important data.

Conclusion

sed is a powerful tool for text processing on the command line. With its help, you can perform complex text transformations efficiently and effectively. Mastery of sed will enhance your productivity in text manipulation tasks.

--

--

Peter Hou
Peter Hou

Written by Peter Hou

I am a Senior Software Engineer and tech lead in a top tech company.

No responses yet