Linux sed Command: How to Install It + Usage Examples

In Unix-like operating systems, sed stands short for stream editor, which performs functions like finding, replacing, inserting, and deleting lines from a specified file or range. It supports regular expression, enabling the program to perform complex pattern matching.

The Linux sed command is most commonly used for substituting text. It searches for the specified pattern in a file and replaces it with the wanted string.

Furthermore, it modifies files line by line, all from within the command line. All changes made on your virtual private server (VPS) using the sed commands are temporary, keeping the original file unaltered.

This article will explain the program’s general syntax, acceptable options, and subcommands. We will also cover 10 basic usages of the sed command.

sed Command Syntax

Here’s what the sed command’s general syntax looks like:

sed options... [script] [input_file...]

You can add the following command line options to modify an operation:

  • -b or --binary – opens input files in the binary mode to make the lines end at a line feed.
  • --debug – switches to debug mode to display the input in canonical form and annotate program execution.
  • --follow-symlinks – edits a symbolic link’s eventual destination. However, it only works when combined with the -i option.
  • --help – prints usage information, bug-reporting address, and exit option.
  • -i or --in-place [=SUFFIX] – performs in-place edits by overwriting the original file.
  • --posix – disables all extensions to POSIX sed and simplifies writing portable scripts.
  • --version – prints sed program’s current version.
  • -E, -r, or --regexp-extended – utilizes extended regular expression.
  • -e <em>script</em> or --expression=<em>script</em> – adds a specified script to run while processing the input.
  • -f <em>script-file</em> – adds the content of a specific script file to run with the command while processing the input.
  • -l <em>N</em> or --line-length=<em>N</em> – specifies the desired line-wrap length for the -l command. Its default value is 70.
  • -n, --quiet, or --silent – disables output printing unless the user uses the -p command.
  • -s or --separate – considers specified files separate, not as a single uninterrupted long stream.
  • --sandbox – ensures sed command only operates on input files in the command line and disables external programs.
  • -u or --unbuffered – minimizes output and input buffer.
  • -z, --null-data, or --zero-terminated – views input as a set of lines that ends with a zero byte.

The subcommands below are GNU sed specific. Some are standard POSIX, while others are GNU sed extensions:

  • a \ text – places a text variable in the output before moving to the following line.
  • e – executes the command and sends the results to the output stream.
  • d – deletes the pattern space and immediately starts the next cycle.
  • D – removes text from the pattern space to the first new line. Restarts the cycle with the resultant pattern space without reading the current string or input.
  • g or G – replaces contents of the pattern space with the ones from the hold space.
  • l – prints the pattern space in an unambiguous form.
  • q [exit-code] – stops processing input, then sed exits.
  • s command or s/regexp/replacement/[flags] – matches the pattern space against the supplied regexp. If found, the program will replace the matched string with a replacement.
  • n or N – prints the pattern space and replaces it with the following line. If there’s no more input, it will exit sed without processing the script.
  • v – makes sed nullify if it doesn’t support the GNU extensions.
  • z – empties the pattern space content.
  • x – exchanges the contents of the hold and pattern spaces.
  • = – prints the current input line number.
  • : – specifies the label location for branch commands, such as b, t, and T.

How to Install the sed Command

The sed package comes pre-built alongside most Linux distributions. However, if you don’t have it installed by default, follow these steps:

  1. Access SSH via your VPS and log in using the sudo account.
  2. Update the current system by typing this command:
sudo apt-get update
  1. Install the sed package by entering the following command:
sudo apt-get install sed
  1. Verify the version by running the command below:
sed --version

sed Command Examples

In the following sections, we will present ten sed examples to grasp the basics of using the sed stream editor.

How to Replace a String Using the sed Command

The sed command is commonly used for replacing text. It will search for a specified pattern in a file and change it with the desired string.

To do it, use the substitution command s and delimiters to separate each field. Replace the “old_string” value with the original name and “new_string” with the preferred text:

sed ‘s/old_string/new_string/’ samplefile.txt

For example, to substitute the word “images” with “photos” in the scenery.txt file, enter the following:

sed ‘s/images/photos/’ scenery.txt

How to Replace the nth Occurrence of a Pattern in a Line Using a sed Command

Insert a corresponding character, either a slash ( / ) or vertical bar ( | ), and substitute the hash ( # ) symbol with the desired number to replace the nth occurrence of a pattern in a line. Here’s the basic syntax:

sed ‘s/old_string/new_string/#’ samplefile.txt

For example, to replace the first occurrence of the word “music” with “song” in a line inside the playlist.txt file, enter:

sed ‘s/music/song/1’ playlist.txt

How to Replace All the Occurrences of the Pattern in a Line Using the sed Command

By default, sed only substitutes the first occurrence of a specified string in every line. It looks for the initial instance, replaces it, and moves on to the following input line.

To replace all the pattern occurrences in one line, add a substitute flag /g for global replacement. Here’s the sed script:

sed ‘s/old_string/new_string/g’ samplefile.txt

For example, to replace all occurrences that contain “eagle” with “falcon” in a line inside animals.txt, run:

sed ‘s/eagle/falcon/g’ animals.txt

How to Replace and Occurrence From nth to All Occurrences in a Line Using the sed Command

To substitute all patterns from the nth to all occurrences in one line, combine the /# and /g.

Here’s the sed script:

sed ‘s/old_string/new_string/#g’ samplefile.txt

For example, the command below replaces the word “pisces” with “aquarius” from the second, third, and fourth occurrences until the last occurrence in the astrology.txt file.

sed ‘s/pisces/aquarius/2g’ astrology.txt

How to Parenthesize the First Character of Each Word Using the sed Command

Here’s the sed command example to print the first character of every word in parenthesis:

echo “desired_sentence” | sed ‘s/\(\b[A-Z]\)/\(\1\)/g’

For example, to display the first character of “An example of the sed command” in parenthesis, enter:

echo “An example of the sed command” | sed ‘s/\(\b[A-Z]\)/\(\1\)/g’

How to Replace String on a Specific Line Number Using Sed Command

To replace the string on a specific line number, add the desired value before s. Here’s the general syntax:

sed ‘#s/old_string/new_string/’ samplefile.txt

For example, to substitute the word “cake” with “bread” in the second line of foods.txt, enter:

sed ‘2 s/cake/bread/’ foods.txt

How to Duplicate the Replaced Line With /p Flag Using the sed Command

To duplicate the replaced line on the terminal window, use the /p or print flag. However, if the line doesn’t have the search pattern and is not substituted, the command only outputs it once.

Here’s the general syntax:

sed ‘s/old_string/new_string/p’ samplefile.txt

For example, to replace the word “phones” with “tablets” on the gadgets.txt file and duplicate the results on the terminal window, run:

sed ‘s/phones/tablets/p’ gadgets.txt

How to Replace String on a Range of Lines Using the sed Command

Add the line numbers to the sed command to replace several strings within a specific range. Replace the first # with the initial text number and the second # with the last row you want to include.

Here’s the basic syntax:

sed '#,# s/old_string/new_string/' samplefile.txt

For example, the command below replaces the last three instances of “germany” located in the third, fourth, and fifth line on the countries.txt file, with the word “france”:

sed ‘3,5 s/germany/france/’ countries.txt

How to Print Only the Replaced Lines With the sed Command

sed displays the entire file content and its substitute text in the output by default. Add the necessary attributes to the command if you have a lot of text and want to highlight the modified lines.

The -n option disables automatic printing, while the p command instructs sed to display strings where substitution occurs.

Here’s the general syntax:

sed -n 's/old_string/new_string/p' samplefile.txt

For example, to replace the third instance of “green” with “blue in a line inside the colors.txt file and print the modified text on the terminal window, enter:

sed -n 's/green/blue/3p' colors.txt

How to Delete Lines From a Particular File Using the sed Command

The delete command removes lines from the current input file without opening the content. There are five sed scripts available:

Deleting a particular line of input using the d subcommand:

sed '#d' samplefile.txt

For example, to remove the first line from the cities.txt file, run the following:

sed ‘1d’ cities.txt

Deleting multiple lines within a specific range:

sed '#,#d' samplefile.txt

Replace the # symbols with the start and end of the line range. For example, to delete the first, second, and third line from the cars.txt file, enter the following:

sed '1,3d' cars.txt

Deleting a file content’s last line:

sed ‘$d’ samplefile.txt

For example, to remove the last line from the computers.txt file, run the following:

sed ‘$d’ computers.txt

Deleting from the nth to the last line:

sed ‘nth,$d’ samplefile.txt

For example, to remove the second to the last input line from the books.txt file, enter:

sed ‘2,$d’ books.txt

Deleting the pattern matching line:

sed ‘/pattern/d’ samplefile.txt

For example, to remove the “oabo” pattern from the filestrings.txt file, run:

sed ‘/oabo/d’ filestrings.txt

Conclusion

sed is a text stream editor that comes built-in with Unix systems and command line shells to perform fundamental text transformations on an input stream. It allows you to select, replace, duplicate, add, delete, and modify a text without opening the file.

As a part of the Linux commands repository, it works by creating one pass over the inputs, making it a more efficient utility than most. It can also filter text in a pipeline, distinguishing the program from other command line editors. Furthermore, it supports regular expression, allowing it to run advanced text matching.

We hope this article has helped you learn more about the sed command. If you have any questions or suggestions, leave them in the comments section below.

Linux sed Command: Frequently Asked Questions

This section will answer the most frequently asked questions about the sed command.

How Is sed Different From grep?

Both sed and grep are text processing tools in Linux. Aside from editing a string, the former offers additional text transformation commands like substitution, which grep doesn’t support.

The grep command is primarily used to find particular text patterns in large files and print the output.

How Is sed Used in the Bash Script?

In the bash script, the sed command has three primary uses – printing to stdout, deleting a text, and replacing a specific string. The program determines which line it will operate on from the specified address range.

How Do You Call a Variable in the sed Command?

A variable is a character we assign a value to, and adding it to the sed command provides better readability. This value can be a number, character, filename, or device. 

The shell expands variables. For example, if the string contains a slash ( / ), use a different delimiter, such as a vertical bar ( | ).

Is sed Faster Than grep?

That depends on the file size. The sed command is faster when you work within a simple text substitution. On the other hand, grep is the quicker option for finding a pattern within large files.

Author
The author

Laura Z.

Laura is an experienced Content Production Lead. With 9+ years of experience in marketing under her belt, Laura loves sharing her ideas with the world. In her free time, she enjoys learning about new marketing trends and watching TV shows on Netflix.

Author
The Co-author

Noviantika G.

Noviantika is a Digital Content Writer at Hostinger. Passionate in web hosting, WordPress, and SEO, she's driven to share her knowledge with the world through her writing. During her free time, Noviantika likes to hop on a plane and discover places.