Using SED Command To Add, Remove, And Replace Text In Files

Today I will be showing you how to replace text in your files using the SED command. You can use this command for far more than what I will be showing but this will at-least get us started. This is great for bash scripts and automating minor changes to configuration files.

Something to keep in mind is that with the examples below, none of the changes will be saved to those files, we will cover saving to files at the end of the guide.

Lets Get Started!

For the sake of this tutorial lets create a quick and simple dummy text file for reference and practice. You can do so with the following command.

echo "cat
dog
bear
monkey" > ~/sed-tutorial.txt

Adding New Line With SED

To add a new line after matching a search term using the SED command, use the following syntax. The cat in the below example will be our search term, and then we will add the word test to the next line.

sed '/cat/a test' ~/sed-tutorial.txt
cat
test
dog
bear
monkey

If you want to add your new line before the match, you can do so as-well by making a quick and easy adjustment (replace the /a with /i).

sed '/cat/i test' ~/sed-tutorial.txt
test
cat
dog
bear
monkey

Replacing Text With SED

If you want to replace a chunk of text you can do so as-well, the example below will replace dog with elephant.

sed 's/dog/elephant/' ~/sed-tutorial.txt
cat
elephant
bear
monkey

A practical example of using this would be something like the following to quickly change the port for ssh:

sed 's/Port/Port 333 # Original Value: /' /etc/ssh/sshd_config

The result would replace the line port assignment with our new port as-well as leave a comment with the original port.

Removing Text With SED

You can also remove text with SED which is great when you don’t want to simply remove an entire line with grep -v. To do this you would use the same as above but simply leave the field for your replacment text blank.

sed 's/dog//' ~/sed-tutorial.txt
test
cat

bear
monkey

Saving Results With SED

As you can see, none of the above examples actually edited the files or saved the changes we want to make. It is always best to do a dry run first just incase but to actually write the changes we will add a -i argument to the SED command. Here is one of the examples above but actually writing the changes to the file.

sed -i '/cat/i test' ~/sed-tutorial.txt

# Checking the actual file:
cat ~/sed-tutorial.txt 
test
cat
dog
bear
monkey

Your other option if you don’t want to write the changes to the same file is to write them to another file, for this method you will not use the -i option but instead simply feed the output into the file you want to create or replace.

sed '/wolf/i test' ~/sed-tutorial.txt > sed-tutorial2.txt

I hope this guide helps you get started with using the SED command, please don’t forget to like, comment, and share for more guides!

Leave a Reply

Protected with IP Blacklist CloudIP Blacklist Cloud