Stream Editor or sed it is one of the most powerful Linux commands that you need to know. The sedcommand allows you to perform a lot of functions like searching, replacing, inserting or deleting. All of these functions can be performed on a text. You can use sed command with files and the most magical part is that you can edit the file without opening it. Besides the previously mentioned functions, the sed command supports regular expressions.
During this tutorial, we will cover the sed command and how to use it. Next, we will show you some useful examples while using the sed command.
First, make sure that the sed command is already installed. You can use the next command to get the version of the installed sed:
For the sake of this tutorial we are going to use the next file:
Linux sed Examples
- Replace every occurrence of an operating system with OS
sed 's/operating system/OS/g' sed_example
- Replace every occurrence of an operating system with OS except for the 4th line.
sed '4!s/operating system/OS/' sed_example
- Add spaces to the left of the text and redirect the output to a new file.
sed 's/^/ /' sed_example > new_sed_example
- Display text starting with “Hello” and ending with “tutorial”.
sed -n '/Hello/,/tutorial/p' sed_example
- Display the lines from the 2nd to the5th.
sed -n 2, 5p sed_example
- Display the whole file except lines from the 2nd to the 5th.
sed 2,5d sed_example
- Double all the spaces in the file.
sed G sed_example
- Delete the last line in the file.
sed '$d' sed_example
- Replace “Linux” with “Unix” in case “test” is not found.
sed '/test/!s/Linux/Unix/' sed_example
- Delete all the lines starting from the 2nd line to the line containing the word “free”.
sed '2,/free/d' sed_example
- Delete all spaces in front of each line in a file.
sed 's/^[ ^t]*//' new_sed_example
- Delete all spaces at the end of each line in a file.
sed 's/[ ^t]*$//' new_sed_example
- Delete all spaces in front and at the end of each line in a file.
sed 's/^[ ^t]*//;s/[ ^]*$//' new_sed_example
- Replace a string for the first instance in a line only.
To replace a string which is found at the beginning of a line only.
sed 's/I/IIII/' sed_example
- Replace a string for the 3rd instance in a line only.
To replace a string which is found for the 3rd time in a line only.
sed 's/a/aaaaaaaaa/3' sed_example
- Replace a string for all instances found in a line.
sed 's/a/aaaaa/g' sed_example
- Replace string in a line if a certain word is found.
sed '/powerful/s/operating system/OS/g' sed_example
- Delete every 2nd line, starting with the 1st line.
sed '1~2d' sed_example
- Print every 3rd line starting with the 2nd line.
sed -n '2~3p'sed_example