SED Command

  • SED Command stand for Stream Editor.
  • It can be used for find,replace,insertion or deletion.
  • This powerful tool can edit file without even opening the files.

Synatx

sed OPTIONS... [SCRIPT] [INPUTFILE...] 
  • Print the contents of demo.txt file using sed
sed "" demo.txt
  • Replace(Substitute) the contents of file and print it
sed "s/o/oo/" demo.txt
sed -i "s/o/oo/" demo.txt   # -i will actullay replace the contents of the file

In the above command s/ stands for substitue and then o/ is the character that has to be searched for and oo/ is the text that is suppose to be replaced if the file.

Note in the above executed command only the 1st o is replaced with oo in a line, all the remaining o in the same line are skipped example is line number 3, the o of the World text is not replaced but o of the text Hello is replaced.

use the attribute g at the end of the command to enable replace all the occurrence in a file

  • Delete the lines which has numbers in it
sed "/[0-9]/d" demo.txt
  • Replace and delete together in a single sed command, replace o with oo and delete all the lines which has number in it
sed "s/o/oo/g; /[0-9]/ d" demo.txt
  • Delete all the blank lines using SED
sed "/^$/d" demo.txt

In the above command ^$ stand for blank line i.e the line start(^) and end($) are both together that means it is a blank line, and the command d stands for delete

Leave a Comment