Sed basics
Print file while replacing replacing a word. |
sed ‘s/old/new/g’ file.txt |
Print file with changes to a new file. |
sed ‘s/old/new/g’ file.txt > newfile.txt |
Change file in place. |
sed ‘s/old/new/g’ -i file.txt |
Change file in place. But make a backup of the original with .backup appended to the file name. |
sed ‘s/old/new/g’ -i.backup file.txt |
Change output of another command by piping it to sed. |
echo ‘old text’ | sed ‘s/old/new/g’ |
Run multiple sed commands from a script. |
echo ‘s/old/new/g’ >> script.sed echo ‘/Hello/d’ >> script.sed sed -f script.sed file.txt |
Run multiple commands from the command line. |
sed -e ‘s/old/new/g’ -e ‘/hello/d’ file.txt |
Replacing text
Replace all occurances of a string. |
sed ‘s/old/new/g’ file.txt |
Replace only the nth occurence of a string in a file. |
sed ‘s/old/new/ 2’ file.txt |
Replace replace a string only on the 5th line |
sed ‘5 s/old/new/’ file.txt |
Replace “world” with “universe” but only if the line begins with “hello” |
sed ‘/hello/s/world/universe/’ file.txt |
Remove “\” from the end of each line. |
sed ‘s/\\$//’ file.txt |
Remove all whitespace from beginning of each line. |
sed ‘s/^\s*//’ file.txt |
Remove comments. Even those that are at the end of a line. |
sed ‘s/#.*$//’ file.txt |
Search for text
Search for a string and only print the lines that were matched. |
sed -n ‘/hello/p’ file.txt |
Case insensitive search. |
sed -n ‘/hello/Ip’ file.txt |
Search for a string but only output lines that do not match. |
sed -n ‘/hello/!p’ file.txt |
Appending lines
Append line after line 2 |
sed ‘2a Text after line 2’ file.txt |
Append line at the end of the file |
sed ‘$a this is the end of the file’ file.txt |
Append line after every 3rd line starting from line 3 |
sed ‘3~3a Some text’ file.txt |
Prepending lines
Insert text before line 5. |
sed ‘5i line number five’ file.txt |
Insert text before each line that matches pattern. Insert “Example:” before each line that contains “hello world” |
sed ‘/hello world/i Example:’ file.txt |
Deleting lines
Delete line 5-7 in file. |
sed ‘5,7d’ file.txt |
Delete every 2nd line starting with line 3. |
sed ‘3~2d’ file.txt |
Delete the last line in file |
sed ‘$d’ file.txt |
Delete lines starting with “Hello”. |
sed ‘/^Hello/d’ file.txt |
Delete all empty lines. |
sed ‘/^$/d’ file.txt |
Delete lines starting with “#” |
sed ‘/^#/d’ file.txt |