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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

awk and variable 1

Status
Not open for further replies.

w5000

Technical User
Nov 24, 2010
223
PL
why awk returns nothing when -va=$P is set?

Code:
# cat test_innp
1 A2 23 A0 A155
2 A1 01 A6 A090
3 A3 10 A1 A015
4 A0 11 A2 A220
5 A4 33 A5 A130
6 A9 06 A3 A085
7 A5 09 AA A060
# awk '$4 ~ /^A0$/ {print $5}' test_innp
A155
# P=A0
# awk -va=$P '$4 == a {print $5}' test_innp
A155
[COLOR=red]# awk -va=$P '$4 ~ /a/ {print $5}' test_innp
# awk -va=$P '$4 ~ "/a/" {print $5}' test_innp
# awk -va=$P '$4 ~ "/$a/" {print $5}' test_innp
# awk -va=$P '$4 ~ "/$a$/" {print $5}' test_innp
# awk -va=$P '$4 ~ "/^$a$/" {print $5}' test_innp
# awk -va=$P '$4 ~ /^$a$/ {print $5}' test_innp
# awk -va=$P '$4 ~ ^a$ {print $5}' test_innp
 Syntax Error The source line is 1.
 The error context is
                $4 ~ >>>  ^ <<< a$ {print $5}
 awk: 0602-500 Quitting The source line is 1.
#
[/color red]
#

 
Hi

Regular expressions literals are not parsed for variables in Awk. Use string instead :
Code:
awk -va=$P '$4 ~ a {print $5}' test_innp [gray]# anywhere[/gray]
awk -va=$P '$4 ~ "^"a {print $5}' test_innp [gray]# anchored at the beginning[/gray]
awk -va=$P '$4 ~ a"$" {print $5}' test_innp [gray]# anchored at the end[/gray]
awk -va=$P '$4 ~ "^"a"$" {print $5}' test_innp [gray]# anchored on both sides[/gray]

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top