Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 715
Orlo Avatar asked Dec 26 '22 14:12

Orlo


2 Answers

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"
like image 105
Stefano Sanfilippo Avatar answered Dec 28 '22 05:12

Stefano Sanfilippo


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.

like image 32
Ed Morton Avatar answered Dec 28 '22 05:12

Ed Morton