cnu
cnu

Reputation: 531

How to get occurrences of word in all files? But with count of the words per directory instead of single number

I would like to get given word count in all the files but per directory instead of a single count. I do get the word count with simple grep foo error*.log | wc -l by going to a specific directory. I would like to get the word count per directory when the directory structure is like below.

Directory tree                 
.
├── dir1
│   └── error2.log
    └── error1.log
└── dir2
     └── error_123.log
     └── error_234.log
 ── dir3
     └── error_12345.log
     └── error_23554.log

Upvotes: 1

Views: 461

Answers (1)

hek2mgl
hek2mgl

Reputation: 158220

Update: The following command can be used on AIX:

#!/bin/bash

for name in /path/to/folder/* ; do
    if [ ! -d "${name}" ] ; then
        continue
    fi
    # See: https://unix.stackexchange.com/a/398414/45365
    count="$(cat "${name}"/error*.log | tr '[:space:]' '[\n*]' | grep -c 'SEARCH')"
    printf "%s %s\n" "${name}" "${count}"
done

On GNU/Linux, with GNU findutils and GNU grep:

find /path/to/folder -maxdepth 1 -type d \
    -printf "%p " -exec bash -c 'grep -ro 'SEARCH' {} | wc -l' \;

Replace SEARCH by the actual search term.

Upvotes: 1

Related Questions