Skip to content

Instantly share code, notes, and snippets.

@FilippoBovo
Last active November 15, 2018 16:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save FilippoBovo/a375d00908a29a18d738a2d8fdb78e97 to your computer and use it in GitHub Desktop.
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, #$@&%*!
SWEAR_WORDS='fudge|motherfather|custard'
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