Andrew Mercer
on this page

Substitute

sed 's/old/new/' file                 # first match on each line
sed 's/old/new/g' file                # all matches on each line
sed -i 's/old/new/g' file             # edit the file in place
sed -i.bak 's/old/new/g' file         # in place, keeping file.bak
sed 's|/usr/local/www|/var/www|g' file       # use another delimiter when the text contains slashes
sed -E 's/([0-9]+)-([0-9]+)/\2-\1/' file    # extended regex with capture groups
sed 's/foo/bar/Ig' file               # case-insensitive (GNU)

Using | as the delimiter avoids the "leaning toothpick" effect of escaping every slash in paths.

Delete and print lines

sed '3d' file                         # delete line 3
sed '2,4d' file                       # delete lines 2-4
sed '$d' file                         # delete the last line
sed '/^$/d' file                      # delete blank lines
sed '/^[[:space:]]*$/d' file          # also lines containing only whitespace
sed '/^#/d' file                      # delete comment lines
sed -n '2p' file                      # print only line 2
sed '2q;d' file                       # print line 2 and quit (fast on big files)
sed -n '10,20p' file                  # print lines 10-20
sed -n '/start/,/end/p' file          # print a range between two patterns
sed G file                            # double-space a file

Trim characters

sed 's/^..//' file                    # remove the first 2 characters (more dots for more)
sed 's/.\{3\}$//' file               # remove the last 3 characters
sed 's/.*\(...\)$/\1/' file          # keep only the last 3 characters
sed 's/:.*//' file                    # delete everything from the first colon on
sed 's/^[^:]*://' file                # delete everything up to and including the first colon
sed -E 's/\s+\S+$//' file            # remove the last whitespace-separated column
sed 's/\t//g' file                    # delete tab characters (a literal ^I)

Search and replace across many files

Find files containing the string first, preview, then run:

grep -rlI 'string1' . | xargs echo sed -i 's/string1/string2/g'      # preview the commands
grep -rlIZ 'string1' . | xargs -0 sed -i.bak 's/string1/string2/g'    # do it, keeping backups

Or with find (see find):

find . -path '*/.git/config' -exec sed -i 's/gitlab.internal.example/gitlab.com/g' {} +

Careful: echo $(sed 3d file) > file (a common trick) collapses newlines. Use sed -i '3d' file instead.

Edit a file's path references

sed -i 's|/usr/local/www/data/site/app_community|/var/www/html/site/app|g' autoloader.php

Notes

  • sed -i differs slightly between GNU sed (-i alone) and BSD/macOS sed (-i '').
  • sed -n turns off automatic printing and p prints explicitly.
  • For column-oriented work, awk is easier. To pull fields, cut.
  • Classic collection of one-liners: sed1line.txt (Eric Pement). A one-page cheat sheet is in the r/linuxadmin thread.