How to awk or grep a variable, without using echo? How to awk or grep a variable, without using echo? bash bash

How to awk or grep a variable, without using echo?


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"abcdeftestghiklmnop$ awk -v var="$var" 'BEGIN{ printf "%s", gensub(/.*(test([^\n]*\n){2}).*/,"\\1","",var) }'testghi$ awk -v var="$var" 'BEGIN{ printf "%s", gensub(/.*(test([^\n]*\n){3}).*/,"\\1","",var) }'testghiklm

With other awks you can use match() + substr() to get the same result.