user968623
user968623

Reputation: 53

How to read word by word from a file in a for loop

This code is to read a directory of text file and match it with the input.txt. I got the word from input.txt working, but I don't know how to extract each word from a text file and compare to it. The file is in paragraph form so I can't look for similar character and such. Is there a way to read every word one by one at a time and compare?

#!/bin/bash

findkeyword () {
    file="$1"   
    keyword="$2"    
    value="$3"

    count=0
    while read line
    do

#problem right here


    set -- $line
    a=$(expr length "$file")
        for i in '$line'; do
                    if [ "$i" = "$keyword" ]; then
                count=`expr $count + 1`;
            fi
            done

    done <$file

    echo "Profile: " $file
    scorefile $value $count
}

scorefile () {
    value="$1"
    count="$2"

    echo "Score: "  $((value * count)) 

}


while read line
        do
        set -- $line
        keyword=$1
            value=$2

        echo "key: " $keyword
        echo "value: " $value

        for xx in `ls submissions/*`
            do
                     filename=$xx
                     findkeyword $filename $keyword $value
            done
        done <input.txt

Upvotes: 1

Views: 9633

Answers (1)

user unknown
user unknown

Reputation: 36229

To count the occurences of a word in a file, just use grep -c (count):

for word in $(<input.txt); do echo -n $word " " ; grep -c $word $file; done  

For different files in a dir, never¹ ever use ls.

 for file in submissions/*
 do
      echo "$file"
      for word in $(<input.txt)
      do
          echo -n "$word " ; grep -c "$word" "$file"
      done
 done 

¹in very, very rare cases, it might be the best solution, but blanks, linefeeds and special characters in filenames will corrupt your commands.

Upvotes: 4

Related Questions