Sed Command Search Replace Delete Add Line Tricks and Tips

sed -e "expression script"
-i to edit in place" Edit and save"

Sed How to Replace slash / And backslash \ character
Slash / represent as Normal /
backslash \ represent as \\
Example:
# cat sedlinux.txt
hi/kumar\kumar/
a)sed 's:\\:/:g' sedlinux.txt [ change back slash \ into slash / ]
hi/kumar/kumar/
b)sed 's:/:\\:g' sedlinux.txt [ change slash / into back slash \ ]
hi\kumar\kumar\

#sed 's:/var/www/html:/home/username:g' filename
|Replace /var/www/html to /home/username
#sed -n '1~3p' filename | Print Every 3rd Line 1st,1+3 4th,7th line.
#sed -n '0~2p' filename | Print Every 2nd LIne 0st,2nd,4th,6th,

#sed '3i New Line' filename.txt | It will add New Line On 3rd Line.
#sed -n '0~2i word' file | Add the new line in 0,2,4,6 th Line.

To delete the line with matching Character

#sed -i '/matchword/d' phone.txt
#sed -i '/^$/d' phone.txt  - ^$ it will delete the empty lines
#sed '0~2d' filename -  d Delete Line - 0,2,4,6

Replace every second occurrence in the line.
#sed ‘s/Search_Word/Replace_Word/2’ filename
Sed Replace with variable
#sed “s/$Search_Variable/$Replace_Variable/g” filename



1)& - matching pattern    sed 's/[0-9]/**&**/g' filename    Replace Every Single Digit with **&**  &- Search Pattern
2)& - matching pattern    sed 's/[0-9]/*&*&/g' filename    Replace Every Single Digit with *&*&- Search Pattern
3)& - matching pattern    sed 's/[0-9]/&&/g' filename    Replace Every Single Digit with &&- Search Pattern
  & - Represent Matching Word  
  *  - Represent N of the Character    




4)Sed 's/^t/Replace_word/g' filename    What are words start with character 't'
5)
sed 's/t$/Replace_word/g' filename    what are  words end with character 't' It will replace word.   Character – Dolor symbol.

6)sed -e '/parttern/,+5d' filename    from the searching patter, it will delete the consecutive 5 lines.
7)
sed -i '/pattern/d' filename    Delete Line where pattern found
8)Sed '/patter/d' filename    Delete matching pattern.

Related post