sed

sed - stream editor for filtering and transforming text.


Replace string (only the first found in each line):

sed 's/old_word/new_word/' file.txt

Replace all strings:

sed 's/old_word/new_word/g' file.txt

Replace string changing the original file:

sed -i 's/old_word/new_word/' file.txt

Replace string in a specific line (third) of the file:

sed '3 s/old_word/new_word/g' file.txt

Replacing string on a range of lines (1 to 10):

sed '1,10 s/old_word/new_word/g' file.txt

Replace multiple spaces followed by just one:

cat file.txt | sed 's/ */ /g'

Replace lowercase by uppercase:

sed 's/[a-z]/[A-Z]/g' myfile.txt

Print the third line of the file:

sed -n '3'p file.txt

Print the replaced line twice on the terminal:

sed 's/old_word/new_word/p' file.txt

Print only the replaced lines

sed -n 's/old_word/new_word/p' file.txt

Delete the fifth line of a file:

sed '5d' file.txt

Delete the first five lines:

sed '1,5d' file.txt

Delete pattern matching line:

sed '/remove_this/d' file.txt

Insert a line in second line:

sed '2i\new second line' file.txt

Append a line after the second line:

sed '2a\second second line' file.txt

Modify a specific line:

$ sed '3c\third line!!' file.txt