Home   Profile   Fun
#61 Linux  03.04.2007

The command sed


Print line 9 of a file.
sed -n '9p' file1.txt

Print the content of the file without line 1 TO 3.
sed '1,3d' file2.txt

Print line 1 AND 3 of a file.
sed -n -e '1p' -e '3p' file3.txt

Print the content of testfile.txt but manipulate the output so that every line begins with an additional "string1". Note: If the file ends with a new line you will see an "additional" string1 at the end. \1 is the back reference to (.*). You may expect a $1 here. But this is not working it must be \1. We have to escape the brackets, so in the end it's \(.*\).
sed 's/\(.*\)/string1\1/' ./testfile.txt

sed prints the modified file content to standard out. If you want to change the file directly use -i -e. This command will delete line 1 TO 3 of the file.
sed -i -e '1,3d' file1.txt


How to remove comments and empty lines

Remove all lines of a file which contain only blanks, tabs or newline.
sed -i -e '/^\s*$/d' testfile.txt

Remove all lines of a file starting with #
sed -i -e '/^#.*$/d' testfile.txt

Remove all lines of a file starting with # including indented lines
sed -i -e '/^\s*#.*$/d' testfile.txt