Results 1 to 2 of 2
Hi everyone!
I've only been scripting for less than a year, and I've run into a problem trying to use the awk command. The ultimate goal is to use awk ...
- 06-24-2009 #1Just Joined!
- Join Date
- Sep 2008
- Posts
- 1
Awk: using a variable as a print argument?
Hi everyone!
I've only been scripting for less than a year, and I've run into a problem trying to use the awk command. The ultimate goal is to use awk to pull values out of a spreadsheet (.csv) and print it in a textfile. I've run into problems because I am trying to code it so that I can specify the variables to print within the awk command:
I've figured out how to do this:
Command:
> grep CVRAM_001_recon cvram_included.csv
Produces:
> CVRAM_001_recon,1.39,-0.2,1.6,0.11,2009/03/04,1,0,1,11,,32,1032,1,12,36.26,162,177,76,82,123, 5.9,1.8,102,195.6,148,43,,0.02,2,67,104.67
I figured out how to reformat it using this:
Command:
> grep CVRAM_001_recon cvram_included.csv | awk -F: 'BEGIN {FS="," ; OFS="\t"} {print "Input",$1,$2,"CVRAM"}'
Produces:
> Input CVRAM_001_recon 1.39 CVRAM
HOWEVER, I want to be able to change the variables (ie - $1,$2)
I have gotten to a point where I have made a variable that has the exact list of items I would like to print out from the spreadsheet, which I am calling $var_list
> echo $var_list
> $12,$15,$19,$20
But remember, this changes based on the variables I want to print out. Ideally, I would like the command above to work like this:
> grep CVRAM_001_recon cvram_included.csv | awk -F: 'BEGIN {FS="," ; OFS="\t"} {print "Input",echo $var_list here,"CVRAM"}'
Which would end up processing as this:
> grep CVRAM_001_recon cvram_included.csv | awk -F: 'BEGIN {FS="," ; OFS="\t"} {print "Input",$12,$15,$19,$20,"CVRAM"}'
> Input 32 12 76 82 CVRAM
Does anyone have any suggestions on how to make a variable read like $? within awk? I really appreciate your time and help!
Thanks so much!
Tori
- 06-25-2009 #2Linux User
- Join Date
- Aug 2006
- Posts
- 458
grep is useless when you are using awk.
Code:var="12,15,19" awk -v var="$var" 'BEGIN{ FS="," } /CVRAM_001_recon/{ m=split(var,v,",") for(i=1;i<=m;i++){ print $(v[i]) } } ' file


Reply With Quote