Using shell variables in an awk script

0 votes

So, I'm trying to find out some ways to pass external shell variables to an awk script, but I'm confused about ' and ".

First, I tried this with a shell script.

$ v=123test
$ echo $v
123test
$ echo "$v"
123test

Then I tried awk.

$ awk 'BEGIN{print "'$v'"}'
$ 123test
$ awk 'BEGIN{print '"$v"'}'
$ 123

Lastly, this is what I tried.

$ awk 'BEGIN{print " '$v' "}'
$  123test
$ awk 'BEGIN{print ' "$v" '}'
awk: cmd. line:1: BEGIN{print
awk: cmd. line:1:             ^ unexpected newline or end of string 

Where is the difference?

Jul 1 in Linux Administration by Upasana
• 8,530 points
62 views

1 answer to this question.

0 votes

Using -v is, imo, The best way because it's most portable.

variable="line one\nline two" awk -v var="$variable" 'BEGIN {print var}' line one line two

This should be compatible with most aw. The variable is available in the BEGIN block as well.

If you're dealing with multiple variables:

awk -v a="$var1" -v b="$var2" 'BEGIN {print a,b}'
answered Jul 1 by Shubham
• 13,300 points

Related Questions In Linux Administration

0 votes
1 answer

How to send mail using linux shell script?

If you've already configured the server, with ...READ MORE

answered Jun 11 in Linux Administration by ajs3033
• 7,280 points
44 views
0 votes
1 answer
0 votes
1 answer

How to take input from user in bash script?

You can use if-else branch to check ...READ MORE

answered Jan 31 in Linux Administration by Omkar
• 67,660 points
42 views
0 votes
1 answer

Setting environment variables in linux

You need to add more information about ...READ MORE

answered May 13 in Linux Administration by ajs3033
• 7,280 points
27 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Adding yes/no/cancel prompts in shell script

You can use the read command. Here's ...READ MORE

answered Mar 12 in Linux Administration by ajs3033
• 7,280 points
38 views
0 votes
1 answer

How to change the default shell in Linux?

1. Change the password file directly for ...READ MORE

answered May 24 in Linux Administration by Upasana
• 8,530 points
31 views
0 votes
1 answer

Comparing two string variables in an 'if' statement in Bash

1. For string comparison, use: if [ "$s1" ...READ MORE

answered May 15 in Linux Administration by Shubham
• 13,300 points
64 views
0 votes
1 answer

“cd” doesn't work in my shell script

One way to get around this is ...READ MORE

answered May 23 in Linux Administration by Shubham
• 13,300 points
44 views