sed
stream editor
Can perform lots of functions on file like searching, find and replace, insertion or deletion.
Here the “s” specifies the substitution operation. The “/” are delimiters. The “search_word” is the search pattern and the “replace_word” is the replacement string.
Note - By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third…occurrence in the line.
Replacing or substituting string
replaces the first occurance of unix
in every line.
Replacing the nth occurrence of a pattern in a line
Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The above command replaces the second occurrence of the word “unix” with “linux” in a line.
Replacing all the occurrence of the pattern in a line
Replacing from nth occurrence to all occurrences in a line
Replacing string on a specific line number
Duplicating the replaced line with /p flag
The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.
Printing only the replaced lines
Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.
Replacing string on a range of lines
You can specify a range of line numbers to the sed command for replacing a string.
Here the $
represents the last line
Deleting lines from a particular file
Deletes the 5th line from starting
To delete last line ->
To Delete line from range x to y
Deletes from 3rd to 6th line
To delete from nth to last line ->
To Delete pattern matching line
Last updated