Reputation: 1
awk noob here.
Fundamentally, I have an awk command, ending in {print $4}, that, when fed to an echo > file command, does not print the value of the requested field. Output is blank.
I'm writing a bash script with the goal of creating a file containing four fields: subject, structure, side, and volume, e.g.
136 Hippocampus Left 3450
And I'm drawing from subject-specific files with a bunch of header lines and then a tab-delimited table of brain structures, volumes and other data.
12 17 3450 3450.7 Left-Hippocampus
The script iterates over these files with loops for subject, then structure and side, and for each combination uses awk to match $side-$struct with the appropriate field in the file, then print the field with the volume. Then it echoes all that data to the outfile.
set volume = `awk -v side="$side" -v struct="$struct" '$5 ~ /$side-$struct/ {print $4}' filename.stats
echo "${subj} ${struct} ${side} ${volume}" >> $outfile
However, the file always shows the first three columns' appropriate values, but never the volume value; that column is blank.
When I run a sample awk command in stdout,
awk '$5 ~ /Left-Hippocampus/ {print $4}' filename.stats
It returns the number I want.
Why won't the script correctly print to $outfile the volume data as well as that for the looped variables?
I've seen people talk about buffering speed, and I've tried flushing; I've fed awk the data file with cat; I've tried printing all variables from awk after declaring them with further -v flags; nothing seems to work. Eventually they all do the same thing, print the first three columns in $outfile and not the fourth.
Thanks in advance for any help, this is driving me nuts! The script's been practically ready to run for over a day now...
Upvotes: 0
Views: 1119
Reputation: 189638
The set
command doesn't do what you are hoping.
The Bourne shell syntax for an assignment is simply
variable=value
with no spaces (use quotes if the value needs to contain whitespace).
So,
volume=$(awk -v side="$side" -v struct="$struct" '$5 ~ (side "-" struct) {print $4}' filename.stats)
Notice also how the variables side
and struct
are now actually used by the script.
However, I'm wondering if you should not be doing all your processing in Awk instead.
Upvotes: 2
Reputation: 2828
Try this
volume=`awk -v side="$side" -v struct="$struct" '$5 ~ /$side-$struct/ {print $4}' filename.stats
echo "${subj} ${struct} ${side} ${volume}" >> $outfile
I've removed the spaces on either side of the '=' sign. I've seen that having a space around the equal sign throws errors when assigning value to a variable
Upvotes: 0