3

I also need the directory name to be outputs as well. What I was able to do is to output the total number of lines in all directories with directory name.

find . -name '*.c' | xargs wc -l | xargs -I{} dirname {} | xargs -I{} dirname {}
Theseven7
  • 65
  • 5
  • Can you re-iterate your requirements with a proper example? Can you explain it more with details? – Inian Jan 21 '17 at 15:27
  • @Inian, basically I want to have the directory path and the number of lines ending with a semicolon in that directory (number of lines from all files in that directory). I can output the total number of lines ending with a semicolon in the directory with ' find . -name '*.c' -print0 | xargs -0 grep '[;]$' | wc -l ' but I have no idea how to get the output by directory. – Theseven7 Jan 21 '17 at 16:22
  • @Inian, did it. – Theseven7 Jan 21 '17 at 16:28

2 Answers2

0

Here is a script:

#!/usr/bin/env bash

for dir in */; do (
    cd "$dir"
    count=$(find . -name '*.c' -print0 | xargs -0 grep '[;]$' | wc -l)
    echo -e "${count}\t${dir}"
) done

If you want numbers for each sub-directory:

#!/usr/bin/env bash

for dir in $(find . -type d); do (
    cd "$dir"
    count=$(find . -maxdepth 1 -name '*.c' -print0 | \
        xargs -0 grep '[;]$' | wc -l)
    echo -e "${count}\t${dir}"
) done

Using -maxdepth 1 makes sure the calculation is only done in the current directory, not its sub-directories. So each file is counted once.

Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
0

I have jumbled up a mixture of bash commands mostly GNU-specific, make sure you have them, GNU grep and GNU Awk

find . -type f -print0 | xargs -0 grep -c ';$' | \
  awk -F":" '$NF>0{cmd="dirname "$1; while ( ( cmd | getline result ) > 0 ) {printf "%s\t%s\n",result,$2} close(cmd) }'

The idea is grep -c returns the pattern count in format, file-name:count, which I am passing it to GNU Awk to filter those files whose count is greater than zero and print the directory of the file containing it and the count itself.

As a fancy one-liner as they call it these days,

find . -type f -print0 | xargs -0 grep -c ';$' | awk -F":" '$NF>0{cmd="dirname "$1; while ( ( cmd | getline result ) > 0 ) {printf "%s\t%s\n",result,$2} close(cmd) }'
Inian
  • 80,270
  • 14
  • 142
  • 161