# match "pattern" against the pattern space and replace the 1st occurrence of each line# with "replacement" if successful matchedsed 's/pattern/replacement/'# you can refer the pattern matching sub-expressions with special escapes \1 through \9# /!\ parenthesis and plus sign must be escaped, otherwise sed will consider it as a simple charactersed 's/^foo\(\w\+\)/\1/'# replace only the 4th instance of each line by adding a numbersed 's/pattern/replacement/4'# replace ALL instances of each file by adding "g"sed 's/pattern/replacement/g'# find lines that contain "foobar" and replace "pattern" with "replacement"sed '/foobar/s/pattern/replacement/g'# search "pattern" and substitute with "replacement" except lines containing "foobar"sed '/foobar/!s/pattern/replacement/g'# if you want to edit files in place, add the flag "-i"sed -i 's/pattern/replacement/g' filename.txt# replace commas with newlines (use \r, not \n)sed 's/,/\r/g'
Selective deletion
# remove last charactersed '$s/.$//'# delete last linesed '$d'# delete lines matching patternsed '/pattern/d'# delete 2nd linesed '2d'# delete the first 10 linessed '1,10d'# delete ALL blank linessed '/^$/d'
Print
# -n flag hides lines not affected by the expression, often useful in print statements# print lines that contain "pattern"sed -n '/pattern/p'# print 2nd linesed -n '2p'
Tricks
# you can perform multiple sed operations# instead ofsed 's/foo/bar/g' | sed 's/bar/popo/g'# you can do thissed -e 's/foo/bar/g' -e 's/bar/popo/g'# or even thissed 's/foo/bar/g;s/bar/popo/g'# you can substitute "/" with another charactersed 's~foo~bar~'# append "foobar" after lines matching "pattern"sed '/pattern/a foobar'# prepend "foobar" before lines matching "pattern"sed '/pattern/i foobar'# append "foobar" after 2nd linesed '2a foobar'# prepend "foobar" before 2nd linesed '2i foobar'# insert 2 blank spaces at beginning of each linesed 's/^/ /'