Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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

like image 578
Another.Chemist Avatar asked Apr 21 '14 15:04

Another.Chemist


People also ask

How do I read a file in awk?

In the typical awk program, all input is read either from the standard input (by default the keyboard, but often a pipe from another command) or from files whose names you specify on the awk command line. If you specify input files, awk reads them in order, reading all the data from one before going on to the next.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

What is awk '{ print $3 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.


1 Answers

Instead of:

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

You need to use:

awk -v r="$r" 'NR==r' Aenumerar
like image 173
anubhava Avatar answered Sep 19 '22 22:09

anubhava