Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sed tutorial by example
# Sed tutorial by example
# Example: Substitute "cat" with "dog" in file.txt
sed 's/cat/dog/g' file.txt
# Here "s" stands for "substitute" and "g" for global. If "g" was not present, only the first occurrence would be substituted.
# The pattern after the first slash, /, is the pattern to look for and the pattern after the second slash is the pattern to substitute.
# Example: Substitute parentheses, (), in string 'Hello, (awesome) World!' with underscores, _.
echo 'Hello, (awesome) World!' | sed -E 's/(.*)\((.*)\)(.*)/\1_\2_\3/'
# Out: Hello, _awesome_ World!
# The -E option allows to use extended regular expressions (ERE). Note that these ERE restrected commands, that are listed in the sed manual.
# The parentheses in the regular expression `(.*)\((.*)\)(.*)` capture the group of characters, which can be used in the substitution part with \1, \2 and \3, where the number indicates the order the the groups.
# Example: Substitute spaces with commas
echo '1 2 3 4' | sed -E 's/ /,/g'
# Out: 1,2,3,4
# Example: Substitue swear words with the profanity symbol, #$@&%*!
echo 'fudge you, custard! You, motherfather!' | sed -E "s/($SWEAR_WORDS)/#\$\@\&\%\*\!/g"
# Out: #$@&%*! you, #$@&%*!! You, #$@&%*!!
# Be careful with profanity; use the inverted commas! The inverted commas, "...", were used, so that the SWEAR_WORDS variable could be replaced in the string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment