Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why not take awk variable for?

Status
Not open for further replies.

Routerdark

Technical User
Aug 26, 2016
6
VE
for I in MAY JUN JUL AUG; do echo $I; cat final_subscriber_mOP.txt | grep -v -e rows -e --- -e s|awk '$1 ~ /$I/ {print $1, $2}' | sort -n | uniq -c; done

Thank you for support.
 
Hi

This is not really an Awk question as Awk can do nothing to access shell variables.

The usual solution is to have the shell expand that variable before the code is passed to Awk. But parameter expansion is not performed on single quoted ( ' ) strings :
Code:
[blue]master #[/blue] I='Something'

[blue]master #[/blue] echo '$1 ~ /$I/ {print $1, $2}'
$1 ~ /$I/ {print $1, $2}

The solution may be to enclose the string in double quotes ( " ), but then the shell will attempt to expand everything looking meaningful for it :
Code:
[blue]master #[/blue] echo [highlight]"[/highlight]$1 ~ /$I/ {print $1, $2}[highlight]"[/highlight]
 ~ /Something/ {print , }

So to make quoting work as you wish, you have to either :
Code:
[gray]# interrupt the single quotes around the shell variable and quote it with double quotes[/gray]
awk '$1 ~ /[highlight]'[red]"[/red][/highlight]$I[highlight][red]"[/red]'[/highlight]/ {print $1, $2}'

[gray]# escape everything you not want the shell to expand[/gray]
awk "[highlight]\[/highlight]$1 ~ /$I/ {print [highlight]\[/highlight]$1, [highlight]\[/highlight]$2}"

Beside those the are 2 more ways the shell can make a value accessible to Awk :
Code:
[gray]# define an Awk variable from outside, using the [b]-v[/b] ( or [b]--assign[/b] ) option[/gray]
awk [highlight]-vJ="$I"[/highlight] '$1 ~ [highlight]J[/highlight] {print $1, $2}'

[gray]# export the variable ( using the [b]export[/b] shell builtin ) so Awk can access it as environment variable[/gray]
awk '$1 ~ [highlight]ENVIRON["I"][/highlight] {print $1, $2}'


Feherke.
feherke.ga
 
Hi Feherke

Thanks you so much. I think that was it. Let me check your solution and let you know.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top