How to Use the sed Command in Linux
Stands for “Stream Editor”. “sed” is a utility command that take file content or standard input (stdin) and modify the output through RegEx pattern. It’s generally a handy command to use to modify content within a file.
General syntax for sed
command:
$ sed [OPTIONS] [FILE]...
Text substitution
echo "Text" | sed 's/Replaceable_Word/The_Word_That_Replaces/'
Use the sed
command to search and replace any part of the text. 's'
indicates a search and replace task.
Example: Finding the word “CSS” in the text “CSS Libraries” and replacing it with the word “JavaScript.”
Replace text on a specific line in a file
sed '[line] s/harder/easier/g' [file]
The 'g'
option of the sed
command is used to replace anything that matches the pattern.
Example: Let’s replace the word “harder” in the first line of the libraries.txt file. Note: “harder” occurs twice in the line.
Replace first matching with new text
sed 's/harder/easier/' [file]
This command replaces only the first match of the search pattern.
Example: Replacing the first occurrence of the word “CSS” in the example.txt file with the word “JavaScript”
Remove matching lines
sed '/Something/d' example.txt
Use the d
option of the sed
command to remove any line from a file.
Example: Deleting those lines in the example.txt file that contain the text “Something”
Search for a case-insensitive word + delete it
sed '/Sample/Id' example.txt
The I
option of the sed
command is used to search for a matching pattern in a case insensitive way.
Example: Finding a line containing the word ‘Sample’ and seeing the line delete with and without option in the example.txt file.
Replace words with uppercase
sed 's/\(libraries\)/\U\1/Ig' example.txt
Use the U
option of the sed
command to convert any text to uppercase letters.
Example: Searching for the word “libraries” in the example.txt file and replacing it with uppercase letters.
Replace words with lowercase
sed 's/\(libraries\)/\L\1/Ig' example.txt
The L
option of the sed
command is used to convert any text to lowercase letters.
Example: Searching for the word “libraries” in the example.txt file and replacing it with lowercase letters.
Insert blank lines in a file
sed G [file]
Use the G
option of the sed
command to insert blank lines after each line of the file.
Example: Displaying the file before using the option. Then we use the command and see that after each line, empty lines appeared.
Print file’s line numbers
sed '=' [file]
The =
sign is used to print a line number before each line of text in a file.
Example: Following the use of the command, the line numbers appear after each line in the example.txt file.