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 2

Status
Not open for further replies.

w5000

Technical User
Nov 24, 2010
223
PL
hello,

how to get it working with variable?

awk '$2 == "astring" {print $1" "$3}' inputfile

so get it working in a script when "astring" is on variable (eg. as $a in a "while read a b c d")

I tried with:
awk '$2 == "$a" {print $1" "$3}' inputfile

but didn;t work.



thank you.

best regards.
 
Hi

This is probably the most frequently asked ( and answered ) AWK question.
Code:
awk '$2 == "'"$a"'" {print $1" "$3}' inputfile

[gray]# or[/gray]

awk "\$2 == \"$a\" {print \$1\" \"\$3}" inputfile

[gray]# or[/gray]

awk -va="$a" '$2 == a {print $1" "$3}' inputfile
The last one should be preferred.

Feherke.
 
Well, don't just show him the fix, tell him "why" too. That cuts down on these kinds of questions. "Teach a man to fish..." and all that. [bigsmile]

w5000, the shell parses the command line before executing it. It's the shell that replaces the environment variables with whatever their value is. The shell only expands/replaces the environment variables if they are in double quotes (like "$this"), or not in quotes at all. If the variables are in single quotes (like '$this'), they are not expanded, but the dollar sign and variiable name are passwd to the program, not what that variable is set to at that point.

So, the fix was to change your single quotes to double quotes so your variables would be expanded.

Also notice the backslashes before a couple quotes in the second example. That's because those need to be passed to the program as quotes, and not terminating the quoted string of characters.

Hope this helps.


 
Just to illustrate what I was saying, try these...
Code:
VAR="Hello!"

echo '$VAR'
echo "$VAR"

echo 'VAR = "$VAR"'
echo "VAR = "$VAR""
echo "VAR = \"$VAR\""


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top