0

I am currently working on a script that will look through the output of nm and sum the values of column $1 using the following

read $filename
nm --demangle --size-sort --radix=d ~/object/$filename | {
    awk '{ sum+= $1 } END { print "Total =" sum }'
}

I want to do the following for any number of files, looping through a directory to then output a summary of results. I want the result for each file and also the result of adding the first column of all the columns.

I am limited to using just bash and awk.

Grisha Levit
  • 8,194
  • 2
  • 38
  • 53
Euler1707
  • 3
  • 2

2 Answers2

0

You need to put the read $filename in a while; do; done loop and feed the output of the entire loop to awk.

e.g.

while  read filename ; do
       nm  ...  $filename 
done  |  awk '{print $0}  { sum+=$1 } END { print "Total="sum}'

the awk {print $0} will print each file's line so you can see each one.

Mike Wodarczyk
  • 1,247
  • 13
  • 18
  • I'd suggest `while IFS= read -r filename` -- that way we're not removing backslashes or leading/trailing whitespace from the input. And quote `"$filename"` on the expansion, perhaps with a `--` preceding to allow filenames starting with dashes to work correctly. (Thus: `nm ... -- "$filename"`) – Charles Duffy Feb 01 '17 at 16:09
  • ...other than that, though, this is a better-considered division-of-labor than having `awk` run the subprocess, given its lack of facilities to allow such to be done securely. – Charles Duffy Feb 01 '17 at 16:10
0

bash globstar option is for recursive file matching
you can use like **/*.txt at the end awk command

$ shopt -s globstar
$ awk '
    BEGINFILE { 
        c="nm --demangle --size-sort --radix=d \"" FILENAME "\"" 
        while ((c | getline) > 0) { fs+=$1; ts+=$1; }  
        printf "%45s %10'\''d\n",FILENAME, fs
        close(c); fs=0; nextfile
    } END { 
        printf "%30s %s\n", " ", "-----------------------------" 
        printf "%45s %10'\''d\n", "total", ts 
    }' **/*filename* 
mug896
  • 1,777
  • 1
  • 19
  • 17
  • If we had a malicious filename -- say, a file created with `touch './$(rm -rf $HOME)'` -- this would be very, very unfortunate. Hopefully nothing like that exists in a directory full of binaries, but it's probably best not to teach folks "this is a good practice to loop over files with awk" if the next person might be looping over an upload directory. – Charles Duffy Feb 01 '17 at 16:07