I'm working with large variables and to speedup my script I'd like to awk
or grep
a variable without using echo/printf
what I've tried:
awk "/test/ {for(i=1; i<=100; i++) {getline; print}}" "$var"
awk: fatal: cannot open file `<<$var content>>' for reading (No such file or directory)
grep -A 100 test "$var"
grep: `<<$var content>>': No such file or directory
In bash you can redirect from a variable to stdin using the one-line heredoc:
awk "/test/ {for(i=1; i<=100; i++) {getline; print}}" <<< "$var"
If I understand you, you have a multi-line string stored in the shell variable var
and you'd like to print 100 lines from the line containing test
in that string inclusive. With GNU awk that'd be:
$ awk -v var="$var" 'BEGIN{ printf "%s", gensub(/.*(test([^\n]*\n){100}).*/,"\\1","",var) }'
e.g. to print "test" plus the 2 or 3 lines after it, inclusive:
$ echo "$var"
abc
def
test
ghi
klm
nop
$ awk -v var="$var" 'BEGIN{ printf "%s", gensub(/.*(test([^\n]*\n){2}).*/,"\\1","",var) }'
test
ghi
$ awk -v var="$var" 'BEGIN{ printf "%s", gensub(/.*(test([^\n]*\n){3}).*/,"\\1","",var) }'
test
ghi
klm
With other awks you can use match() + substr() to get the same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With