8️⃣sed

stream editor

Can perform lots of functions on file like searching, find and replace, insertion or deletion.

sed 's/<search_word>/<replace_word>/<options>' filename

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.

  1. Replacing or substituting string

sed 's/unix/linux/' file.txt

replaces the first occurance of unix in every line.

  1. Replacing the nth occurrence of a pattern in a line

sed 's/unix/linux/2' file.txt

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.

  1. Replacing all the occurrence of the pattern in a line

sed 's/unix/linux/g' file.txt
  1. Replacing from nth occurrence to all occurrences in a line

sed 's/unix/linux/3g' file.txt
  1. Replacing string on a specific line number

sed '3 s/unix/linux/' file.txt
  1. Duplicating the replaced line with /p flag

sed 's/unix/linux/p' file.txt

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.

  1. Printing only the replaced lines

sed -n 's/unix/linux/p' file.txt

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.

  1. Replacing string on a range of lines

You can specify a range of line numbers to the sed command for replacing a string.

sed '1,3 s/unix/linux/' file.txt
sed '2,$ s/unix/linux/' file.txt

Here the $ represents the last line

  1. Deleting lines from a particular file

sed '5d' filename.txt

Deletes the 5th line from starting

To delete last line ->

sed '$d' filename.txt
  1. To Delete line from range x to y

sed '3,6d' filename.txt

Deletes from 3rd to 6th line

To delete from nth to last line ->

sed '3,$d' filename.txt
  1. To Delete pattern matching line

sed '/pattern/d' filename.txt

Last updated