简体   繁体   中英

How to pass shell variable to awk command inside shell script

I just want to pass a shell variable that stores name of a file to awk command. When I searched this problem on the net I see many different options but none of them worked for me. I tried the followings:

#!/bin/bash
for i in "$@"
do
case $i in
    -p=*|--producedfile=*)
    PFILE="${i#*=}"
    shift # past argument=value
    *)
          # unknown option
    ;;
esac
done
echo "PRODUCEDFILE  = ${PFILE}"
awk  -v FILE=${PFILE} '{print FILE $0}' #DIDNT WORK
awk   '{print FILE $0}' ${PFILE} # DIDNT WORK
awk  -v FILE=${PFILE} '{print $0}' FILE #DIDNT WORK

To pass a shell variable to awk , you correctly used -v option.

However, the shift was unnecessary (you're iterating options with for ), ;; was missing (you have to terminate each case branch), as well as was the name of the file for awk to process. Fixed, your script looks like:

#!/bin/bash
for i in "$@"; do
    case $i in
        -p=*|--producedfile=*)
            PFILE="${i#*=}"
            ;;
        *)
             # unknown option
            ;;
    esac
done

echo "PRODUCEDFILE = ${PFILE}"
awk  -v FILE="${PFILE}" '{print FILE, $0}' "${PFILE}"

Note however, awk already makes the name of the currently processed file available in the FILENAME variable. So, you could also write the last line as:

awk '{print FILENAME, $0}' "${PFILE}"

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