计算输入文件中字符串的出现次数

时间:2012-01-23 10:02:18

标签: linux bash shell

有一个shell脚本应该处理传入的文本文件。

此文本文件包含多行分割的字符串,每个字符串不止一次出现。

shell脚本需要读取此文本文件并输出每个字符串的字符串和计数。

考虑文本文件是:

  蒂姆

     

时间

     

马克

     

标记

     

艾伦

     

ALLen

     

ALLEN

输出应该是这样的:

  蒂姆出现2次

     

Mark出现2次

     艾伦出现3次

现在,我能够打印字符串的出现,但是重复字符串出现的次数,即“Tim出现2次”被打印两次。我一旦计算它的出现,我就试图用NULL替换一个字符串,但由于某种原因,sed不起作用,因为我可能没有在正确的地方(或以正确的方式)调用它

 #!/bin/bash

INPUT_FILE="$1"
declare -a LIST_CHARS

if [ $# -ne 1 ]
then
        echo "Usage: $0 <file_name>"
        exit 1
fi


if [ ! -f $INPUT_FILE ]
then
        echo "$INPUT_FILE does not exists. Please specify correct file name"
        exit 2
fi

while read line
do
        while read i
        do
                echo $line
                count=`grep -i $line | wc -l`
                echo "String $line appears $count times"
        done < $INPUT_FILE

done < $INPUT_FILE

4 个答案:

答案 0 :(得分:11)

你也可以使用sort和uniq with flags来忽略大小写:

sort -f FILE | uniq -ic

简单sed命令可以将输出格式更改为指定的格式:

s/^ *\([0-9]\+\) \(.*\)/\2 appears \1 times/

答案 1 :(得分:8)

经典的awk解决方案类似于:

$ awk 'NF{ count[ toupper( $0 ) ]++} 
    END{ for ( name in count ) { print name " appears " count[ name ] " times" };
}' input

答案 2 :(得分:1)

假设data.txt包含您的单词,以下脚本将会执行。

while read line
do  
    uc=$(echo $line | tr [a-z] [A-Z] | tr -d ' ')
    echo  $uc $(grep -i "$uc" strs.txt | wc -l)
done< data.txt | sort | uniq

输出

31
ALLEN 6
MARK 4
MOKADDIM 1
SHIPLU 1
TIM 4

另一种选择是

sort -f data.txt | uniq -i -c  | while read num word
do  
    echo $(echo $word|tr [a-z] [A-Z])  appeard  $num times
done

注意:我看到您的文本文件包含空行。所以输出中的31包含空行数。

答案 3 :(得分:1)

for i in `sort filename |uniq -c``
do
    # --if to print data as u like--
done
相关问题