Some more advanced examples of how to use the sed command in Linux.
- Add a character to the beginning of a line (e.g. the | character):
sed -e 's/^/\|/' orig.txt > new.txt
- Change a file from Unix to Windows format (i.e. add a \r at the end of the line):
sed -e 's/$/\r/' myunix.txt > mydos.txt
- Change a file from Windows to Unix format (i.e. remove the last character of each line):
sed -e 's/.$//' mydos.txt > myunix.txt
- Replace the first occurence of foo by bar on all lines:
sed -e 's/foo/bar/' myfile.txt
- Replace all occurences of foo by bar on all lines:
sed -e 's/foo/bar/g' myfile.txt
- Delete the lines 1 to 4 and 6 to 9:
sed -e '1,4d' -e '6,9d' myfile.txt
- Delete all empty lines from a UNIX file:
sed -e '/^$/d' myfile.txt
- Delete all empty lines from a Windows file:
sed -e '/^\r$/d' myfile.txt
- Delete all comments and empty lines from a UNIX configuration file:
sed -e '/^#/d' -e '/^$/d' /etc/vsftpd/vsftpd.conf
More information on: