Skip to content

Instantly share code, notes, and snippets.

@sebastiancarlos
Last active June 8, 2023 05:38
Sample sed script
#n <- run sed in -n mode
# This sed script operates on a list of books in the format:
# Title
# Author
# Rating (1 to 5 asterisks)
# --- (separator)
# Is returns every author who has written a book with 'the'
# in the title and a 4 or 5 star rating.
# This is meant to illustrate the use of the hold and
# pattern space. If you really need something like this, use
# multiple commands or something like awk or perl.
# Append three lines to pattern space.
N ; N ; N
# Check for 'the' in title and 4+ star rating.
/.*the.*\n(.*)\n\*{4,5}\n---/I {
# Replace pattern space with
# capture group (author name.)
s//\1/
# Append pattern space to hold space.
H
}
# On last line.
$ {
# Swap pattern and hold space.
x
# Remove starting newline
# (it's there by default on hold space.)
s/^\n//
# Replace newlines with commas.
s/\n/, /g
# Print pattern space.
p
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment