I have a text file that has information for several locations. Each new section in the file has a header. I am trying to take all the information under a single header, strip out the header, and move it to a separate file. All sections move to a separate file based on header information. I am programming this in a shell script using ksh running on aix.

awk '/FILE-HDRPQ/{x=substr ($0,11,6)}NR>1{print $0 > $TRANSDIR"/"x"_prchgrpt.txt";}' $TRANSDIR/$prcfile

FILE-HDRPQ is the first part of the header. $0 contains all columns from that header until the line before the next header. x=an identifying number in the header which is used to create the filename that $0 (minus the top header line) will dump into.

Variables $TRANSDIR and $prcfile help us name the file and place it in the proper directory. These variables are called out earlier in the script.

I am now getting

awk: 0602-562 Field $() is not correct.

when I run the script. Can't for the life of me figure out what is wrong. I have tried playing with single and double quotes.

  • If one of the answers solved your problem please indicate so with the check mark next to it.
    – Jeff Schaller
    Jul 1, 2017 at 12:05

2 Answers 2


awk is always trying to interpret $<something> as a field value (e.g. $0 - the whole record, $3 - the third field, $NF - the last field value)

Pass directory name via variable:

awk -v dir="$TRANSDIR" '/FILE-HDRPQ/{x=substr ($0,11,6)}
       NR>1{print $0 > dir"/"x"_prchgrpt.txt";}' "$TRANSDIR/$prcfile"
  • You are awesome - I was looking at the wrong var. Thanks so much. Jun 30, 2017 at 19:37
  • @GingerBeard76, you're welcome Jun 30, 2017 at 20:15

You should pass the TRANSDIR variable to awk explicitly, like that:


and then use it like this:

print $0 > TRANSDIR

inside the awk script.

  • You guys are amazing - I was barking up the wrong tree trying to figure out what was wrong with $0 - thanks so much. Saved my bacon today. Free internets all around! Jun 30, 2017 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.