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, 2019 in Linux Administration by Upasana
• 8,590 points
490 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, 2019 by Shubham
• 13,380 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, 2019 in Linux Administration by ajs3033
• 7,280 points
97 views
0 votes
1 answer

How do I use a shell script to SSH in to a remote machine to execute commands?

Your first problem can be solved like ...READ MORE

answered Jun 27, 2019 in Linux Administration by ajs3033
• 7,280 points
1,363 views
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, 2019 in Linux Administration by Omkar
• 69,040 points
120 views
0 votes
1 answer

Setting environment variables in linux

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

answered May 13, 2019 in Linux Administration by ajs3033
• 7,280 points
81 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, 2019 in Linux Administration by ajs3033
• 7,280 points
553 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, 2019 in Linux Administration by Upasana
• 8,590 points
150 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, 2019 in Linux Administration by Shubham
• 13,380 points
115 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, 2019 in Linux Administration by Shubham
• 13,380 points
228 views