I've spent over an hour poking at this. It can't be this hard... I want to print a column of data from one file to another file. The column I want to print is dependent on what is passed in and stuff happening earlier in the script, but it is called COL. The file I need to pull the information from is called $1.db, $1 being the first argument passed in (already checked that it exists). What I have currently:

awk -v colvar="$COL" '{ print $colvar }' "$1.db"  >> tmp2.tmp

This results in the entire contents of $1.db being printed to tmp2.tmp, not just the column.

When I sh -xv it, I see

awk -v colvar="$COL" '{ print $colvar }' "$1.db"  >> tmp2.tmp
+ awk -v colvar=3 '{ print $colvar }' cop4342.db

So, I see that the awk var is being set to the value of COL, but it isn't being substituted inside the print statement. I suspect that is due to the single quotes, but don't know what to do about it. Any help appreciated : )

  • Are you sure you have FS set correctly?
    – Thor
    Sep 29 '12 at 18:11
  • I don't know what FS signifies in this context, so I'm going to go with no... I'm new to this.
    – Lauren
    Sep 29 '12 at 18:17
  • If you're referring to my file privileges, I have confirmed earlier in the script that I have read and write privileges on all files I'm referencing.
    – Lauren
    Sep 29 '12 at 18:24
  • 1
    FS is the field-separator, e.g. if you have comma-separated data call awk with -F,. It's hard to tell you more without some sample input. I recommend you read the the awk manual page man awk.
    – Thor
    Sep 29 '12 at 18:34
  • The field separator is a single space - the default for awk. I'll add sample input to the question. I've read the man page, just didn't remember the term FS. Thanks for taking a look at it for me.
    – Lauren
    Sep 29 '12 at 18:42

If all you want to do is extract a column of data, you can just use cut. For example, if file example.dat contains

a b c d e
1 2 3 4 5

then cut -d ' ' -f 3 example.dat gives


The field separator here is a space, and we are selecting column three.

Edit: This bash script calls awk to produce the equivalent output:


awk '{print $colvar}' colvar=$1 example.dat
  • I'm feeling really dumb right about now. Thanks! For knowledge sake, any idea what is wrong with the awk I wrote?
    – Lauren
    Sep 29 '12 at 18:51
  • The problem is I don't know what col it will be. The column number is a variable which is set earlier in the script.
    – Lauren
    Sep 29 '12 at 18:57
  • @Lauren - see my edit, which accepts a variable and works here. Sep 29 '12 at 19:22

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.