Sir Robert Sir Robert - 1 year ago 67
Linux Question

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?

Answer Source

You can use this for loop:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download