1. Perform a find a replace within a file and echo contents back to standard output (which can be redirected to a file)
$ sed 's/[search string]/[replace string]/g' [filename]
example: change all hello to goodbye in file.txt and save to file2.txt
$ sed 's/hello/goodbye/g' file.txt > file2.txt
2. Perform a find and replace within a file and save contents back to original file
$ sed -e -i 's/[search string]/[replace string]/g' [filename]
example: change all hello to goodbye in file.txt
$ sed -e -i 's/hello/goodbye/g' file.txt
3. Insert a line above a match
$ sed 's/[search string]/[string to add before match]\n&/g' [filename]
example: this example add the text "hey there" before the line which matches "^hello". Remember the ^ denotes that the match must be at the start of a line
$ cat file.txt
hello world
$ sed 's/^hello/hey there\n&/g' file.txt
hey there
hello world
4. Insert a line after a match
$ sed 's/[search string]/&\n[string to add before match]/g' [filename]
example: this example add the text "hey there" after the line which matches "world". Remember the $ denotes that the match must be at the end of a line
cat file.txt
hello world
$ sed 's/world$/&\nhey there/g' file.txt
hello world
hey there