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 [OPTIONS] [FILE]...
echo "Text" | sed 's/Replaceable_Word/The_Word_That_Replaces/'
sed command to search and replace any part of the text.
's' indicates a search and replace task.
Replace text on a specific line in a file
sed '[line] s/harder/easier/g' [file]
'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.
Remove matching lines
sed '/Something/d' example.txt
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
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
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
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]
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]
= 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.