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

喜夏-厌秋 提交于 2020-01-14 06:10:11

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/7719628/how-to-read-word-by-word-from-a-file-in-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!