如何从for循环中的文件逐字阅读

时间:2011-10-10 22:59:57

标签: bash unix loops

此代码用于读取文本文件的目录,并将其与input.txt匹配。我从input.txt工作得到了这个词,但我不知道如何从文本文件中提取每个单词并与之进行比较。该文件是段落形式,所以我不能寻找类似的字符等。有没有办法一次一个一个地读取每个单词并进行比较?

#!/bin/bash

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

    count=0
    while read line
    do

#problem就在这里


    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 个答案:

答案 0 :(得分:2)

要计算文件中某个单词的出现次数,只需使用grep -c(count):

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

对于目录中的不同文件,永远不要使用ls。

 for file in submissions/*
 do
      echo "$file"
      for word in $(<input.txt)
      do
          echo -n "$word " ; grep -c "$word" "$file"
      done
 done 
在非常非常罕见的情况下,它可能是最好的解决方案,但文件名中的空格,换行符和特殊字符会破坏您的命令。