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,620 points
2,689 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,490 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,300 points
1,231 views
0 votes
2 answers

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

Sorry in advance for any formatting. Check out ...READ MORE

answered Feb 7, 2021 in Linux Administration by anonymous
17,312 views
0 votes
1 answer

How do I check if a directory exists in a Bash shell script?

To check if a directory exists in ...READ MORE

answered Jun 7, 2022 in Linux Administration by Korak
• 5,820 points
1,813 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,220 points
1,138 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 13, 2019 in Linux Administration by ajs3033
• 7,300 points
4,230 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,620 points
1,011 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,490 points
1,749 views
0 votes
1 answer

“cd” doesn't work in my shell script

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

answered May 24, 2019 in Linux Administration by Shubham
• 13,490 points
1,858 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP