Reputation: 115
I'm trying to pass a variable, $formula
into an awk script:
[node2 filtering]$ echo $formula
$25 ~ "1/1" && $24 ~ "1/1" && $23 ~ "1/1" && $22 ~ "1/1" && $21 ~ "1/1" && $20 ~ "1/1" && $19 ~ "1/1" && $18 ~ "1/1" && $17 ~ "1/1" && $16 ~ "1/1" && $15 ~ "1/1" && $14 ~ "1/1" && $13 ~ "1/1" && $12 ~ "1/1" && $11 ~ "1/1" && $10 ~ "1/1"||$10 ~ "0/1" && $11 ~ "0/1" && $12 ~ "0/1" && $13 ~ "0/1" && $14 ~ "0/1" && $15 ~ "0/1" && $16 ~ "0/1" && $17 ~ "0/1" && $18 ~ "0/1" && $19 ~ "0/1" && $20 ~ "0/1" && $21 ~ "0/1" && $22 ~ "0/1" && $23 ~ "0/1" && $24 ~ "0/1" && $25 ~ "0/1"
I'm trying to pass into the following to filter my text file, but when I do no filtering happens. I don't get an error either.
awk -F\\t -v myvar="$formula" 'myvar {print $0}' myfile
This works:
awk -F\\t '$10 ~ "0/1" + $11 ~ "0/1"+ $12 ~ "0/1"+ $13 ~ "0/1"+ $14 ~ "0/1"{print $0}' myflies
The reason I'm trying to do this is that I have a simple for loop, which creates $formula
based on the number of columns I want to filter. The number of columns I decide to filter upon is simply based on the number of subjects in the experiment and will always be $10
to $(10+n)
where n is the number of subjects.
Any ideas or tips would be greatly appreciated as to how to solve this problem or construct my script in a different manner?
Here's the silly for loop to construct $formula
:
blah1=$(echo "")
blah2=$(echo "")
for (( i=1; i <= $NUMBEROFSUBJECTS; i++ ))
do
l=$(echo $(( i + $minus )))``
if [ $i == 1 ] ; then
blah1=$(echo " \$$l ~ \"1/1\" ")
blah2=$(echo " \$$l ~ \"0/1\" ")
else
inter1=$(echo " \$$l ~ \"1/1\" ")
blah1=$(echo $inter1 + $blah1)
inter2=$(echo " \$$l ~ \"0/1\" ")
blah2=$(echo $blah2+$inter2)
fi
done
formula=$(echo $blah1 " || " $blah2)`
Here's where I got the awk -F\\t -v myvar="$formula" 'myvar {print $0}'
idea from:
Howto Pass A String as Parameter in AWK within Bash Script
edit: Answer that worked for me ended up being:
awk -F\\t "$formula"'{print $0}' myfile
Thanks so much everyone. Sorry it ended up being so simple.
Upvotes: 1
Views: 509
Reputation: 3361
Do something like this:
formula="$blah1|$blah2"
...
awk "/$formula/ {...}"
So the proposal is to skip the variable definition and just rely on the shell substitution.
Upvotes: 2