Created
December 15, 2024 12:44
-
-
Save samunders-core/f844bd04c58ae9fd2a4cde343ef100d4 to your computer and use it in GitHub Desktop.
multi-expression grep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lookup() { # [awk_options] regex [regex ...]; like grep, but prints all first matches on success, everything when failed | |
! set +"${-//[^x]/}" > /dev/null 2> /dev/null || RESTORE_TRACING="set -x" | |
CMDS=' | |
BEGIN { delete PATT[0] } | |
BEGINFILE { if (FILENAME != "" && FILENAME != "-") { PATT[length(PATT)] = FILENAME; nextfile } } | |
function matchesAny(text) { for (i in PATT) if (text ~ PATT[i]) { delete PATT[i]; return 1 } } | |
{ allLines = allLines "" RS "" $0 } | |
matchesAny($0) { matched = matched "" RS "" $0 } | |
0 == length(PATT) { exit } | |
END { system(length(PATT) ? "date >&2" : "true"); printf(length(PATT) ? "Seen " NR " lines since " START "\n" : "") > "/dev/stderr"; print(length(PATT) ? allLines : matched); exit(length(PATT)) } | |
' | |
for (( COUNT=$#;COUNT>0;COUNT-- )); do | |
[ ! "${!COUNT#-F}" = "${!COUNT}" -o ! "${!COUNT#-v}" = "${!COUNT}" -o "${!COUNT}" = "--" ] && { | |
gawk -v "START=$(date)" "${@:1:$COUNT}" "$CMDS" "${@:$((COUNT+1))}" '-' | |
return | |
} | |
done # explicit gawk due to use of length(...) function | |
gawk -v "START=$(date)" "$CMDS" "$@" '-' | |
RV=$? | |
$RESTORE_TRACING | |
return $RV | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment