Skip to main content

Edit text in a scriptable manner.

# To replace the first occurrence of a regular expression in each line of a file, and print the result:
sed 's/<regex>/<replace>/' <filename>

# To replace all occurrences of an extended regular expression in a file, and print the result:
sed -r 's/<regex>/<replace>/g' <filename>

# To replace all occurrences of a string in a file, overwriting the file (i.e. in-place):
sed -i 's/<find>/<replace>/g' <filename>

# To replace only on lines matching the line pattern:
sed '/<line_pattern>/s/<find>/<replace>/' <filename>

# To delete lines matching the line pattern:
sed '/<line_pattern>/d' <filename>

# To print only text between n-th line till the next empty line:
sed -n '<n>,/^$/p' <filename>

# To apply multiple find-replace expressions to a file:
sed -e 's/<find>/<replace>/' -e 's/<find>/<replace>/' <filename>

# To replace separator / by any other character not used in the find or replace patterns, e.g., #:
sed 's#<find>#<replace>#' <filename>

# To print only the n-th line of a file:
sed '<n>q;d' <filename>

# ---

# BSD-flavor: To replace all occurrences of a string in a file, overwriting the file (i.e. in-place) (https://unix.stackexchange.com/a/92907):
sed -i '' 's/<find>/<replace>/g' <filename>

# To reverse the order of lines in a file using sed (https://www.baeldung.com/linux/reverse-order-of-file-lines#2sed-script-to-reverse-a-file):
sed '1!G;h;$!d' <filename>