Replacing text

Replace all occurrences of a string

$ sed 's/old/new/g' file.txt

Replace only the nth occurrence of a string

$ 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
Comments