Another.Chemist
Another.Chemist

Reputation: 2559

How to pass filename through variable to be read it by awk

Good day,

I was wondering how to pass the filename to awk as variable, in order to awk read it.

So far I have done:

echo    file1   >  Aenumerar
echo    file2   >> Aenumerar
echo    file3   >> Aenumerar

AE=`grep -c '' Aenumerar`
r=1
while [ $r -le $AE ]; do
    lista=`awk "NR==$r {print $0}" Aenumerar`
    AEList=`grep -c '' $lista`
    s=1
    while [ $s -le $AEList ]; do
        word=`awk -v var=$s 'NR==var {print $1}' $lista`
        echo $word
    let "s = s + 1"
    done
let "r = r + 1"
done

Thanks so much in advance for any clue or other simple way to do it with bash command line

Upvotes: 5

Views: 872

Answers (2)

ruakh
ruakh

Reputation: 183612

Judging by what you've posted, you don't actually need all the NR stuff; you can replace your whole script with this:

while IFS= read -r lista ; do
    awk '{print $1}' "$lista"
done < Aenumerar

(This will print the first field of each line in each of file1, file2, file3. I think that's what you're trying to do?)

Upvotes: 5

anubhava
anubhava

Reputation: 786349

Instead of:

awk "NR==$r {print $0}" Aenumerar

You need to use:

awk -v r="$r" 'NR==r' Aenumerar

Upvotes: 6

Related Questions