Skip to content

Instantly share code, notes, and snippets.

Last active October 19, 2016 09:09
What would you like to do?
# Print (note that print lines are duplicated as the match line and the standard output is printed)
sed 'p' /etc/passwd
# Print lines but standard output is suppressed
sed -n 'p' /etc/passwd
# Print lines 1 to 5
sed -n '1,5 p' /etc/passwd
# Print lines fullfilling regex
sed -n '/^root/ p' /etc/passwd
# Substitute bin through binary
# An optional range can be specified in front
sed 's/bin/binary/' /etc/passwd
# Substitute bin through binary but also replace multiple matches in one line
sed 's/bin/binary/g' /etc/passwd
# Substitute bin/bash through bin/sh
# As the search and replacement string contain / another delimiter can be chossen, here @
sed 's@/bin/bash@/bin/sh@' /etc/passwd
# Substitute and print only changes
sed -n 's/bin/binary/p' /etc/passwd
# Write changes to file and backup original file with i-option
sed -i.bak 's/bin/binary/' /etc/passwd
# Insert line before line starting with 'root'
sed '/^root/ i line to be inserted' /etc/passwd
# Insert line after line starting with 'root'
sed '/^root/ a line to be appended' /etc/passwd
# Delete line starting with 'root'
sed '/^root/ d' /etc/passwd
# Multiple sed expressions in the command line
sed '{
/^root/ i line to be inserted
/^root/ a line to be appended
/^root/ d
}' /etc/passwd
# Using a sed script file
sed -f myscript.sed /etc/passwd
# Uppercase 1st column, lowercase 2nd column in comma-separted file with substituting grouping
# Substitution group \([^,]*\) means everything else than a comma
sed 's/\([^,]*\),\([^,]*\)/\U\1,\L\2/ file.csv
# Substitute and subsequently execute
sed 's/^/sudo useradd/e user.list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment