#!/bin/bash if [[ "$1" == '--help' || "$1" == '-h' ]] then echo "Usage: parent-urls [--with-original]" >&2 echo "Take URLs on stdin, remove path components one by one and print the resulting URLs on stdout." >&2 echo "If --with-original is given, the input URL is printed before the parents." >&2 fi prog='' prog+='BEGIN { FS="/"; OFS="/" }' # Set the field separators if [[ "$1" == '--with-original' ]] then prog+='{ print }' # Print the input URL (if desired) fi prog+='/[?#]/ { sub(/[?#].*/, "") }' # Remove query and fragment if present prog+='/\/$/ { --NF }' # Remove the trailing blank field if the URL ends with a slash prog+='{ for (i = NF; i > 3; --i) { --NF; print $0 OFS; } }' # One by one, remove the last path component, print remaining fields exec awk "${prog}"