2012-01-23 137 views
4

有一個應該處理傳入文本文件的shell腳本。計算輸入文件中字符串的出現次數

此文本文件包含分割成多行的字符串,並且每個字符串都存在多次。

shell腳本需要讀取此文本文件並輸出每個字符串的字符串和計數。

考慮文本文件是:

馬克

馬克

艾倫

艾倫

艾倫

輸出應該是這樣的:

蒂姆出現2次

馬克出現2次

阿倫出現3次

權現在,我能夠o打印出現字符串,但重複出現字符串的次數,即「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 

回答

8

經典AWK解決方案是這樣的:

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

+1,儘管不是'/./',您可以使用'NF '這將跳過空行就好了。 –

+0

@jaypal很好的建議。並且能夠更好地處理帶有空白的行。編輯。 –

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包含空白行數。

+0

這是'O(n²)'如果data.txt是strs.txt的副本 – Benoit

+0

@ Benoit-是的,但我也想不到在單個迭代文件中實現目標的方式。 – Incognito

+0

@Benoit:我的解決方案應該更快。 – choroba

11

您也可以sort和uniq使用帶有標誌忽略大小寫:

sort -f FILE | uniq -ic 

簡單sed命令可以改變輸出格式到指定的一個:

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

偉大的一行:-)'sort -f FILE | uniq -ic | sed's/^ * \(。* \)/ \ 2出現\ 1次/'' –

1
for i in `sort filename |uniq -c`` 
do 
    # --if to print data as u like-- 
done 
相關問題