5

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

ruakh
  • 175,680
  • 26
  • 273
  • 307
Another.Chemist
  • 2,386
  • 3
  • 29
  • 43

2 Answers2

6

Instead of:

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

You need to use:

awk -v r="$r" 'NR==r' Aenumerar
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    +1: @Alejandro: Read [this](https://www.gnu.org/software/gawk/manual/html_node/Using-Shell-Variables.html) for more details. – jaypal singh Apr 21 '14 at 15:39
  • I'm pretty sure that those two commands are equivalent (provided `$r` is actually a valid integer), aside from the problem of `$0` being expanded by Bash before calling AWK. Can you explain why you think they're different? – ruakh Apr 21 '14 at 15:47
  • 1
    That's true, `$0` is being expanded – Another.Chemist Apr 21 '14 at 15:50
5

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?)

ruakh
  • 175,680
  • 26
  • 273
  • 307