logan
logan

Reputation: 8346

awk command not working as expected when bash variable is used inside

I tried to use bash variable inside awk by creating a variable in awk command as below. but it does not work it seems

b=hi
$ echo "hihello" |awk -v myvar=$b -F"$0~myvar" '{print $2}'

Actual Output is :

<empty / nothing printed >

Expected output is :

hello

Upvotes: 0

Views: 143

Answers (2)

Tiago Lopo
Tiago Lopo

Reputation: 7959

Why don't you do this:

b=hi ; echo "hihello" | awk -F"$b" '{print $2}'
hello

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Try the below awk command. Put the Field Separator inside BEGIN block.

$ b=hi; echo "hihello" | awk -v myvar=$b  'BEGIN{FS=myvar}{print $2}'
hello

It sets the value of myvar variable to the Field Separator. Thus inturn printing the second column will give you the string hello

Upvotes: 0

Related Questions