Jannah Theme License is not validated, Go to the theme options page to validate the license, You need a single license for each domain name.
DevOpsLinux

Linux sed Command: From Basics to Advanced Usage

Introduction

The Linux sed command, which stands for stream editor, edits text that comes from a file as well as standard input. The non-interactive editing tool sed performs line-by-line changes.

This implies that you specify each of the editing choices while you call the command, as sed automatically carries out the instructions. Although this can be difficult to understand or appear unconventional, this method of text transformation is very effective and quick, particularly when used as a component of a script and automated processes.

You will find out the syntax needed to use this editor in this guide, which also covers several fundamental actions. Sed won’t likely ever be a substitute for your primary text editor, however, it’ll probably end up being a useful tool in your toolkit. Using simple-to-follow instances discover how to navigate the Linux sed command along with its various options.

Linux sed Syntax

The primary syntax associated with the sed command in Linux is as follows:

sed OPTIONS... [SCRIPT] [INPUTFILE...]

sed Linux Options

These command-line options are available for sed to run with:

-b, –binary Access input files using binary mode to treat line feeds as the end of a line.
–debug Use the debug mode for printing input in its correct format and comment on how the program is running.
–follow-symlinks In case the supplied file represents a symbolic link, modify the final destination. The -i option get required for it to function.
–help Specify the usage details.
–i, –in-place [=SUFFIX] By overwriting the initially created file, make edits in place.
–posix For easier portability of scripts, disable all POSIX sed extensions.
–version Give a list of the sed versions active on the system.
-E, -r, –regexp-extended Make use of expanded regular expressions.
-e script, –expression=script To run alongside the commands, add a specific script.
-f script-file Specify a script-file along with adding its contents to the command line.
-l N, –line-length=N The default value associated with the l command’s line-wrap length is 70, therefore you have to provide a different length.
-n, –quiet, –silent Deactivate printing from the output.
-s, –separate View the selected files individually rather than as one long stream of continuous data.
–sandbox Disable running external programs and use the command line alone to work with input files.
-u, –unbuffered Cut back on the input and output buffers.
-z, –null-data, –zero-terminated  View the input being a collection of lines, each of which terminates with a zero byte.

Linux sed Examples

The ten most popular sed commands in Linux, examples, as well as syntax get listed below.

The following text got typed into an example file called foxinbox.txt to illustrate this guide:

  • Knox in box.
  • Fox in socks.
  • Knox on fox in socks in box.
  • Socks on Knox and Knox in box.
  • Fox in socks on box on Knox.

Remember that unless told, sed doesn’t change the source file. On the other hand, the command’s results reveal the modifications done by the supplied command.

When saving the changes, utilize the -i option to overwrite the initial file. Before verifying the command output, it is not advised to engage in such a practice.

As an alternative, save the changes to a unique (or new) file. Add > newfilename.txt to the very last line of the command to reroute the output.

Also Read: Learn to use SCP Command in Linux

Replace String Using the sed Command

Most often, text replacements get done using the Linux sed Command. It looks for the supplied structure in a file and then changes it with the requested string.

Apply the delimiters (often slashes – /) to separate text fields alongside the substitute commands for replacing text using sed.

In light of this, the syntax to use for substituting text is:

sed 's/old_string/new_string/' filename.txt

Both old_string as well as new_string should be changed to reflect the new text you intend to use in its place.

Perform the following command to substitute the word bin for scenarios of the word box:

sed 's/box/bin/' foxinbox.txt
sed 's/box/bin/' foxinbox.txt

The influenced words are seen in the output together with the original content.

Use the sed Command to Replace any Possible Instances of a String

The first instance of the provided string in each line is all that gets replaced by default when using sed. It looks for the very first occurrence of the chosen term in a line, changes it, and afterward proceeds on to the subsequent line.

When there are multiple occurrences of the term box in a single line, the command merely replaces the first one.

Add the g flag to the command to modify all occurrences of the same term when it appears more than once in a single line.

The following command can be used to replace a specific string everywhere it appears in a text:

sed 's/old_string/new_string/g' filename.txt

If you want to consistently substitute the term box with the phrase bin in the file foxinbox.txt, format:

sed 's/box/bin/g' foxinbox.txt

The command substituted every single instance of the term box, as evidenced by the result shown above.

Replace Specific Occurrence in a Line Using the sed Command

Selecting which instance of a given string you would like to get substituted inside each line is possible using the sed program. Add a flag with a number, like 1, 2, etc., to accomplish this:

sed 's/old_string/new_string/#' filename.txt

Employ the following command, for instance, to replace the word bin after the word box on every single line of the text:

sed 's/box/bin/2' foxinbox.txt
sed 's/box/bin/2' foxinbox.txt

Due to their order in the command, each of the initial three occurrences of the term got skipped, while only the final one got replaced.

Only Print Lines With Substitute Text

The output of the sed command on Linux by standard includes both the original text and the substituted text. Add the necessary properties to the command when you’re working with a great deal of text and wish to highlight the lines where the modifications got made.

Employ the following syntax to print only the lines that, in the circumstances specified, have substitutions:

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

In contrast to the substitute command p, which tells sed to print lines wherever replacement happens, the -n option stops automated printing.

Like in the following example, you can supplement other commands with the p command:

sed -n 's/box/bin/2p' foxinbox.txt
Only Print Lines With Substitute Text

The command substitutes the second occurrence of the word box within a line and outputs the line that got changed. 

Replace String Using the sed Command and Ignore Case

By using Linux sed command, the design, takes the case into account. Like the word “fox,” which has both upper- and lowercase initial letters in the text below:

  • Knox in box.
  • Fox in socks.
  • Knox on fox in socks in box.
  • Socks on Knox and Knox in box.
  • Fox in socks on box on Knox.

Perform the following command instead to replace the word “fox” across all situations.

sed 's/fox/cow/' foxinbox.txt

When the word “fox” appears entirely in lowercase, the command’s outcome only affects those instances:

When replacing text, add i sed command at the final part of the command to disregard the case:

sed 's/old_string/new_string/i' filename.txt

Considering the text above, the command to change the word “fox” between upper- and lowercase is thus:

sed 's/fox/cow/i' foxinbox.txt
sed 's/fox/cow/i' foxinbox.txt

As can get seen in the output, the command modified all three cases of the provided string.

Replace String in Specific Line Using the sed Command

By introducing the line number as a prefix in the s subcommand, the Linux  sed command enables you to replace a string in a particular line:

sed '# s/old_string/new_string/' filename.txt

Use the following command to switch the word socks just on the fourth line of the example foxinbox.txt file to the word sandals to evaluate this functionality:

sed '4 s/socks/sandals/' foxinbox.txt
sed '4 s/socks/sandals/' foxinbox.txt

The result reveals that even though the word “socks” has got changed to “sandals” in the fourth line, it still appears in the first instance.

Replace String Only in Specific Range of Lines Using the sed Command

When you would like sed to substitute several occurrences of a string inside a line range rather than the whole thing, you have to give the range. As for the syntax:

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

By changing the primary # to the start line number plus the next # to the latest line number you wish to include, you can add more lines.

As an example, to substitute the word sandals for the final two occurrences of the word socks in the file foxinbox.txt (found in the fourth and sixth lines), carry out:

sed '4,6 s/socks/sandals/' foxinbox.txt
Replace String Only in Specific Range of Lines Using the sed Command

Delete Specific Line Using the sed Command

Through the Linux sed command, employ the d subcommand as well as the following syntax to remove a line from a file:

sed '#d' filename.txt

Execute the command and substitute the hash (#) symbol for the line number you would like to remove.

Using the foxinbox.txt file as an example, type: to delete the second line.

sed '2d' foxinbox.txt
Delete Specific Line Using the sed Command

Delete Lines Within a Specific Range of Lines Using the sed Command

The sed command’s syntax is as follows to remove several lines from a line range:

sed '#,#d' filename.txt

The start and finish of the line range should be used as a substitute for the hash symbols. For example, these:

sed '2,4d' foxinbox.txt
Delete Lines Within a Specific Range of Lines Using the sed Command

This command clears outlines two, three, and four from the file.

Delete From Specific to Last Line Using the sed Command

Utilize the following command to remove all lines between a particular line number as well as the last line:

sed '#,$d' filename.txt

This command should be used to delete anything in foxinbox.txt starting at line 

sed '3,$d' foxinbox.txt
Delete From Specific to Last Line Using the sed Command

Also Read: 14 Tar Command in Linux

Conclusion

This guide demonstrated the method to edit a file using the Linux sed command line using the text stream editor SED. Decide whether to keep the old file after you have updated the text and saved the latest version of it. And how to use sed command in Linux, you will be prepared to discover how you can quickly change a text file.

Arpit Saini

He is the Director of Cloud Operations at Serverwala and also follows a passion to break complex tech topics into practical and easy-to-understand articles. He loves to write about Web Hosting, Software, Virtualization, Cloud Computing, and much more.

Related Articles