简体   繁体   中英

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

Why don't you do this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM