Skip to content

Instantly share code, notes, and snippets.

@jhoblitt
Last active September 26, 2017 21:45
Show Gist options
  • Save jhoblitt/c401c842d37c6f685dc26d63e6f76a0f to your computer and use it in GitHub Desktop.
Save jhoblitt/c401c842d37c6f685dc26d63e6f76a0f to your computer and use it in GitHub Desktop.
regex
# https://stackoverflow.com/questions/15965073/return-code-of-sed-for-no-match
# https://unix.stackexchange.com/questions/145402/regex-alternation-or-operator-foobar-in-gnu-or-bsd-sed
# POSIX ERE + GNU
echo " 13.0-10-g692d0a9 d_2017_09_14 " | sed -E '/^\s*([0-9.-]+g(\S+)|([0-9.]+)\+?[0-9]*).+/,${s//\2\3/;b};$Q1')
# pure POSIX ERE -- does not work on OSX
echo " 13.0-10-g692d0a9 d_2017_09_14 " | sed -E '/^[[:space:]]*[[:digit:].-]{1,}g([[:xdigit:]]{1,})[[:space:]]{1,}.*/!{/^[[:space:]]*([[:digit:]\.]{1,})(+[[:digit:]]{1,}){0,1}[[:space:]]{1,}.*/!b};s//\1/'
# python 2.7 / 3 compat -- can not be done on oneline?
echo " 13.0-10-g692d0a9 d_2017_09_14 " | python -c "
import sys,re;
for line in sys.stdin:
foo = re.sub(r'^\s*(?:[\d.-]+g(\S+)|([\d.]+)\+?[\d]*)\s+.*', lambda m: m.group(1) or m.group(2), line)
if foo is line:
sys.exit(1)
print(foo)
"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment