Skip to content

Instantly share code, notes, and snippets.

@gzagatti
Last active August 1, 2018 18:32
Show Gist options
  • Save gzagatti/139e319f1d251537368003672096b9ad to your computer and use it in GitHub Desktop.
Save gzagatti/139e319f1d251537368003672096b9ad to your computer and use it in GitHub Desktop.
List complete nodes which have a given child using sed.
# sometimes we have a hierarchical list and we want to print all of the nodes
# that have a certain child, simple regular expression will only yield the child
# not the whole node. We can use sed to recover the whole node.
#
# let's say we want to recover all packages in pipenv graph that use pandas.
# /^ /!x{...}
# all of lines which do not start with a space are at the top of the
# hierarchy, swap them with the hold space. The hold space has now the node
# and the pattern space contains the contents of the hold space. Execute all
# commands between brackets.
#
# /pandas/p
# if we were at a node, we would have swapped the contents of the pattern
# space with those of the hold space. In this case, we are lookin at the node
# and all its children. Is `pandas` in there? Then print it.
# if we are not at a node, we are lookin at a single line. This line will
# never have a newline character. Thus, even if we had pandas in there we
# would not print it.
#
# /^ /H
# if we are looking at one of the children, then just append it to the hold
# space.
pipenv graph | sed -n -e '/^ /!{;x; /pandas/p;}; /^ /H'
# similarly, we can find only the options we want, with the respective context with the below
pipenv run pytest --help | sed -E -n -e '/^ *--?/{;x; /(deselect|ignore)/p;}; /^ *--?/!H'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment