String Bash:如何计算文件中字符串的出现次数?

String Bash:如何计算文件中字符串的出现次数?,string,bash,awk,grep,String,Bash,Awk,Grep,我有一个类似以下内容的文件: dog cat dog dog fish cat 我想在Bash中编写一些代码,使文件的格式如下: dog:1 cat:1 dog:2 dog:3 fish:1 cat:2 你知道怎么做吗?该文件非常大(>30K行),因此代码应该有点快 我在想某种循环 像这样: while read line; echo "$line" >> temp.txt val=$(grep $line temp.txt) echo "$val

我有一个类似以下内容的文件:

dog
cat
dog
dog
fish
cat
我想在Bash中编写一些代码,使文件的格式如下:

dog:1
cat:1
dog:2
dog:3
fish:1
cat:2
你知道怎么做吗?该文件非常大(>30K行),因此代码应该有点快

我在想某种循环

像这样:

while read line; 
     echo "$line" >> temp.txt
     val=$(grep $line temp.txt)
     echo "$val" >> temp2.txt
done < file.txt 
读行时
;
echo“$line”>>temp.txt
val=$(grep$line temp.txt)
echo“$val”>>temp2.txt
完成
然后粘贴-d':'file1.txt temp2.txt


然而,我担心这会很慢,因为你要一行一行地走。其他人怎么想?

您可以使用这个简单的
awk
为您完成这项工作:

awk '{print $0 ":" ++freq[$0]}' file


以下是我的想法:

declare -A arr; while read -r line; do ((arr[$line]++)); echo "$line:${arr[$line]}" >> output_file; done < input_file
declare-A arr;而read-r行;do((arr[$line]+);echo“$line:${arr[$line]}”>>输出文件;完成

首先,声明哈希表arr。然后读取for循环中的每一行,并使用读取行的键增加数组中的值。然后回显该行,后跟哈希表中的值。最后一个附加到文件“out”中。

Awk或sed非常强大,但它不是bash,这里是bash的变体

raw=( $(cat file) ) # read file
declare -A index    # init indexed array

for item in ${raw[@]}; { ((index[$item]++)); } # 1st loop through raw data to count items
for item in ${raw[@]}; { echo $item:${index[$item]}; } # 2nd loop change data

请出示您的答卷,只需更新原始问题!是的,它会非常慢,并且会由于部分匹配而产生不正确的值,并且它还存在其他问题,例如它会损坏某些输入,根据输入值和运行它的目录会有不同的行为,等等。请参见。这是否回答了您的问题?对于中等大小的输入文件(比同等的awk脚本慢几个数量级)来说,这需要很长时间才能运行,对于shell来说,这不是一个好的应用程序。看见
raw=( $(cat file) ) # read file
declare -A index    # init indexed array

for item in ${raw[@]}; { ((index[$item]++)); } # 1st loop through raw data to count items
for item in ${raw[@]}; { echo $item:${index[$item]}; } # 2nd loop change data