2014-10-31 65 views

回答

0

如果你願意用awk,你可以做這樣的事情:

$ awk -F] -vRS="," '!(NR%2){++a[$1]}END{for(i in a)printf "%s: %s\n",i,a[i]}' <<<"[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]" 
whatever_str: 1 
another_str: 1 
the_str: 2 

設置字段分隔符],將記錄分隔到,。計算每秒記錄的發生次數。所有記錄處理完畢後,打印結果。

4
# read strings into an array, excluding [, ] and , characters 
IFS='[],' read -r -a strings <<<'[[some_str,another_str],[some_str,the_str],[some_str,the_str],[some_str,whatever_str]]' 

# store counts in an associative array 
declare -A counts=() 
for string in "${strings[@]}"; do 
    [[ $string ]] || continue 
    (('counts[$string]' += 1)) 
done 

# iterate over that associative array and print counters 
for string in "${!counts[@]}"; do 
    echo "$string: ${counts[$string]}" 
done 
+0

需要bash 4或更高的關聯數組。另外還有一些IFS/read/heredoc/herestring錯誤,在某些bash 4+版本中修復,這些錯誤可能與此處不太相關(不幸的是我忘記了這些細節)。 – 2014-10-31 14:01:30

+0

編輯後的當前版本(謝謝,@gniourf_gnioruf)可以在4.0.35上重新使用,所以我不認爲我們依賴於最近的任何修復。 – 2014-10-31 14:04:09

+0

看起來像我正在考慮的問題是將'IFS'泄漏到重定向,並且是'4.3'中修復的'4.2'錯誤。所以是的,這很好。 (爲了記錄,它從來沒有我的意圖來質疑這個事實。) – 2014-10-31 16:13:56