相关疑难解决方法(0)

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

有一个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 …
Run Code Online (Sandbox Code Playgroud)

linux bash shell

4
推荐指数
2
解决办法
9317
查看次数

标签 统计

bash ×1

linux ×1

shell ×1