Apr 18, 2022

sed examples

Ref: https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/

sed 's/unix/linux/' test.txt   # Replacing or substituting string (sed command replaces the first occurrence of the pattern in each line and it)

sed 's/unix/linux/2' test.txt  # Replacing the nth occurrence of a pattern in a line

sed 's/unix/linux/g' test.txt  # Replace all occurances in a line as well

sed 's/unix/linux/3g' test.txt # Replace nth till last (3rd, 4th, 5th etc.,)

echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g'

sed '3 s/unix/linux/' test.txt # restrict the sed command to replace the string on a specific line number.

sed 's/unix/linux/p' test.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.

sed -n 's/unix/linux/p' test.txt # print only replaced lines, n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.

sed '1,3 s/unix/linux/' test.txt # Replace range of lines

sed '5d' test1.txt  # delete 5th line

sed '$d' test1.txt  # delete last line

sed '3,6d' test1.txt # delete from range x to y

sed '12,$d' test1.txt # delete from nth line till last

sed '/abc/d' test1.txt # delete line which matches pattern


# Replace & update same file (-i means --in-place)
sed -i 's/ABC/ABCDEF/g' sed_test.txt

# Replace & update same file (-i means --in-place), -ibak takes original file as backup (sed_test.txtbak)
sed -ibak 's/ABC/ABCDEF/g' sed_test.txt