Skip to content

Instantly share code, notes, and snippets.

@ormaaj
Created August 11, 2011 23:38
Show Gist options
  • Save ormaaj/1141086 to your computer and use it in GitHub Desktop.
Save ormaaj/1141086 to your computer and use it in GitHub Desktop.
Cut a glob from both ends of a string in one command without storing an intermediary value.
#!/usr/bin/env bash
shopt -s extglob
a='aaabbbbccccc'
# Could be half this length if string assignment in an arithmetic context worked, or if the "foo" in ${#foo} could be any expression rather than a parameter.
echo "${a:b=$(b=${a%${a##*(a)}}; echo ${#b}),b:$(c=${a%%*(c)}; echo ${#c})-b}"
# Equivalent to any of:
# tmp="${a##*(a)}"; echo "${tmp%%*(c)}"
# [[ $a =~ a*(b*)c* ]] && echo "${BASH_REMATCH[1]}"
# vim: fenc=utf-8 ff=unix ts=4 sts=4 sw=4 ft=sh nowrap et :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment