Software >> OS >> Unix >> Shell >> Commands >> sed >> Examples of how to use sed


(1)  To remove blank lines from a text file named server.log
 

sed '/^$/d' server.log > /tmp/server.log.blankremoved
 

sed search for lines that have nothing between ^ (begin of line) and $ (end of line) and then deletes (d) them.  Redirect the output to a new file


(2) Search sourcefile and replace foo with bar and output to destfile

sed s/foo/bar/ sourcefile >destfile (3) Print between line X and Y of a text file

sed -n 'X,Yp' textfile.txt


(3)  To remove a string from a line in a file

For example we have a file with the following line - CLASS="--class gnu-linux --class gnu --class os --unrestricted"
We want to remove --unrestricted from that line.

Below is the output before removing:-

grep ^CLASS /var/tmp/test.txt
CLASS="--class gnu-linux --class gnu --class os --unrestricted" 

Remove it and then check the result

sed -i "/^CLASS=/s/ --unrestricted//"  /var/tmp/test.txt
grep ^CLASS /var/tmp/test.txt
CLASS="--class gnu-linux --class gnu --class os" (4) To replace a string in a file with a new string e.g. replace webapp2 with webapp22 in main.py sed -i -e 's/webapp2/webapp22/' main.py