Friday, December 7, 2007

Using a variable as awk's print field specifier


If you have the following input string:

1 to 6 : shirts and tops| 7 and 8 : shirts and tops| 9 to 11 : shirts and tops|12 : shirts and tops

Try This:

FieldCounter='1'
until [ $FieldCounter -gt $GirlsFieldCount ]
do
echo "$GirlsRanges" | awk -F"," "{print $$FieldCounter}"
((FieldCounter = FieldCounter + 2))
done

To pull out every other field.

I had a hard time figuring this one out! The key is double quotes around the print statement instead of single (usually it's '{print $1}'), then escaping the dollar sign so it wouldn't print the value of $$... then I had it.

No comments: