josecampos josecampos - 4 months ago 6
Bash Question

get column numbers that are equal to X

imagine that I've the following string:

1 0 1 1 1


a simple implementation to get the column numbers that are equal to "1" is:

for column_number in $(seq 1 5); do
zero_or_one=$(echo "1 0 1 1 1" | cut -d' ' -f$column_number)
if [ "$zero_or_one" -eq "1" ]; then
echo "$column_number"
fi
done


however, as my strings tend to be very long, that loop takes ages (~ 1min).
is there any other way using for example awk, sed, ..., to get the column numbers that are equal to "1" or "0" ?

expected output if I'm looking for "1":

1
3
4
5


expected output if I'm looking for "0":

2

Answer

It's not clear from your question but this MAY be what you want:

$ awk -v RS=' ' '$0{print NR}' <<<'1 0 1 1 1'
1
3
4
5

$ awk -v RS=' ' '!$0{print NR}' <<<'1 0 1 1 1'
2
Comments