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

Inc*_*ito 4 linux bash shell

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

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

shell脚本需要读取此文本文件并输出每个字符串的String和count.

考虑文本文件是:

蒂姆

蒂姆

标记

标记

艾伦

艾伦

艾伦

输出应该是这样的:

蒂姆出现2次

马克出现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
Run Code Online (Sandbox Code Playgroud)

cho*_*oba 11

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

sort -f FILE | uniq -ic
Run Code Online (Sandbox Code Playgroud)

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

s/^ *\([0-9]\+\) \(.*\)/\2 appears \1 times/
Run Code Online (Sandbox Code Playgroud)


Wil*_*ell 8

经典的awk解决方案如下:

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