简体   繁体   中英

How to use bash variable as awk input file

There is one line of awk in the middle of bash script throws error and I don't know how to fix.

Here is a simplified example:

#!/bin/bash
filename=$(find -L . | grep file.txt.gz | awk '{printf "<(gunzip -c %s)", $1}' )
awk '{print $1}' ${filename} 

When running this script, I got the following error messages:

++ find -L .
++ grep file.txt.gz
++ awk '{printf "<(gunzip -c %s)", $1}'
+ filename='<(gunzip -c ./file.txt.gz)'
+ awk '{print $1}' '<(gunzip' -c './file.txt.gz)'
awk: fatal: cannot open file `<(gunzip' for reading (No such file or directory)

The problem comes from extra ' inside bash variable '<(gunzip' -c './file.txt.gz)' , but I don't know where the ' comes from?

Any suggestions would be helpful.

From the awk man page:

 -v var=val --assign var=val Assign the value val to the variable var, before execution of the program begins.

Hence, if you invoke your awk program by

awk -v P1="$1" '{printf "<(gunzip -c %s)", P1}'

you should get the desired effect.

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