SED Command

·

2 min read

SED Command

SED command in UNIX stands for stream editor and it can perform lots of functions on files like searching, finding and replacing, insertion or deletion. Though most common use of the SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is a much quicker way to find and replace something in a file, than first opening that file in VI Editor and then changing it.

  • SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution).

  • SED command in UNIX supports regular expression which allows it to perform complex pattern matching.

To Find & Replace strings

To find and replace a string and display the output on the terminal

[File won't be changed]

sed 's/<old_string>/<new_string>/g' <file_name>

To make changes to the file

sed -i 's/<old_string>/<new_string>/g' <file_name>

For case insensitive replace

sed 's/<old_string>/<new_string>/ig' <file_name>

To find and replace string only on the 4th line

sed '4s/<old_string>/<new_string>/g' <file_name>

To find and replace only from 4th line to 6th line

sed '4,6s/<old_string>/<new_string>/g' <file_name>

To find and replace only from 4th line to end of the file

sed '4,$s/<old_string>/<new_string>/g' <file_name>

To Delete lines

To delete the 2nd line of the file

sed '2d' <file_name>

To delete from 2nd line to the 4th line of the file

sed '2,4d' <file_name>

To delete from 2nd line to the end of the file

sed '2,$d' <file_name>

To Print the Lines

To print the 2nd line of the file

sed -n '2p' <file_name>

To print from the 2nd line to the 4th line of the file

sed -n '2,4p' <file_name>

To print from 2nd line to the end of the file

sed -n '2,$p' <file_name>

To print from 4th line and 7th line

sed -n '4;7p' <file_name>