0

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
4
  • Not sure I get it, $PFILE is the name of the file Awk should process on (or) just be passed to the body? Commented Sep 28, 2017 at 16:42
  • @Inian $PFILE is the name of file Awk should process as you said. Let's say this is inside the bash script named mybash.sh. Then I call the following command: bash mybash.sh -p=inputfile.txt Commented Sep 28, 2017 at 16:44
  • 3
    So why didn't awk '{print FILE $0}' ${PFILE} work? Remember FILE variable is undefined here. I am sure this would have printed the contents of inputfile.txt one line at a time Commented Sep 28, 2017 at 16:46
  • If you're calling it with an argument -p=inputfile.txt, then there's no need for the shift. You would shift if you called it with -p inputfile.txt, in which case the ${i#*=} doesn't work. Drop the shift. Commented Sep 28, 2017 at 17:01

1 Answer 1

2

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}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.