Reputation: 635
I have a sript that use nearly same code like below:
almsource=`awk -F# '{print $5}' test.csv`
for var in ${almsource[@]}
do
...
done
almSev=`awk -F# '{print $3}' test.csv`
for var in ${almSev[@]}
do
...
done
...
Since most of the code are the same, except the value in awk -F# '{print $3}'
.
And I want to write a function, as extrat the field value in awk -F# '{print $3}' as varaible.
Below is my function, but it seems
awk -F# '{print ${$varNum}}' is not correct.
getFieldGrp()
{
#getFieldGrp <fieldVar>
varNum=$1
almfield=`awk -F# '{print ${$varNum}}' test.csv`
...
done
}
Can anyone help me with it?
Thanks a lot!
Upvotes: 0
Views: 452
Reputation: 247260
Don't need awk for this
getFieldGrp() { cut -d '#' -f $1 test.csv; }
for word in $(getFieldGrp 5); do ...
Upvotes: 2
Reputation: 54592
You need to first pass the shell variable to awk
and use an array to hold all the values. Try this:
array=($(awk -F "#" -v num="$1" '{ print $num }' test.csv))
Upvotes: 2