Sir Robert
Sir Robert

Reputation: 4946

Print the file name after summing a column in the file

I'm using bash and I have a directory that has a bunch of files that look like this:

$ cat myFile.txt
 128 foo bar baz
4891 cat dog
  36 fish cat
 942 potato pants
 ...

I would like to create an output like this:

myFile.txt 5194
another.txt 4920
...

and so on. I know how to sum the files using:

cat myFile.txt | awk '{print $1}' | paste -sd+ - | bc

But I don't know how to re-print the file name. In particular, I want to be able to do it without knowing the filename in advance, like this:

cat *.txt | awk '{print $1}' | paste -sd+ - | bc | ... something here?

Upvotes: 1

Views: 100

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Using awk

awk 'function p(){if(pf)print pf,s;s=0}FNR==1{p()}{s+=$1;pf=FILENAME}END{p()}' *.txt

Better Readable

awk '
       function p(){
           if(pf)print pf,s;
           s=0
       }
       FNR==1{
               p()
       }
       {
           s+=$1;
           pf=FILENAME
       }
       END{
            p()
       }
    ' *.txt

Test Results

[akshay@localhost tmp]$ ls *.txt
f1.txt  f2.txt

[akshay@localhost tmp]$ cat f1.txt 
1
2
3

[akshay@localhost tmp]$ cat f2.txt 
128
1
2

[akshay@localhost tmp]$ awk 'function p(){if(pf)print pf,s;s=0}FNR==1{p()}{s+=$1; pf=FILENAME}END{p()}' *.txt
f1.txt 6
f2.txt 131

Upvotes: 0

anubhava
anubhava

Reputation: 785196

You can use this for loop:

for f in *.txt: do
   awk '{sum+=$1} END{print FILENAME, sum}' "$f"
done

print statement in awk will print both input filename and sum.

Upvotes: 1

Related Questions