Manela Ferreira
Manela Ferreira

Reputation: 29

How do I use for command to give me an output by file?

I have a folder named Chapters which contains 20 files with 1 chapter of a book per file.

I have a file named book_chap.list which contains the list of chapters. It contains something like this:

chap_00
chap_01 

I have a third file called book.names10 which contains a list of names. It contains something like this:

Name1
Name2

What I need from the output is a file that indicates by chapter the times each name has been said in each chapter. Something like this:

chapters/chap_01:Name1
chapters/chap_01:Name1
chapters/chap_01:Name2

I am using this:

for a in chapters/chap_* ;
  do
    echo -n $a;
    ggrep -F -f book.names10 -w -o $a | wc -l ;
done

but the only thing I got is a list of the number of times the names were used in each chapter in general. I don't know where to integrate the file book_chap.list on this command.

Upvotes: 0

Views: 97

Answers (1)

Caílin
Caílin

Reputation: 51

Quick and dirty (you might want to prettify the output):

#!/bin/bash
for chapter in $(ls chapters/chap_*); do
    echo "Chapter ${chapter}:" >> nameOccurences.txt
    for name in $(cat book.names10); do
            echo -n "${name}: " >> nameOccurences.txt
            grep -o ${name} ${chapter} | wc -l >> nameOccurences.txt
    done
echo "" >> nameOccurences.txt
done

If you want to group the result by name rather than chapter, you have to exchange the loops and output accordingly.

Upvotes: 1

Related Questions