1

基本上我的问题是这样的,我有一个由句点分隔的字符串,我希望能够在新行上打印每个单词以及它旁边出现的次数。

这是我已经拥有的:编辑:

#!/bin/bash
PARAM=$1 
FILE=${1-test.txt}
#echo $FILE

temp=$( tr '\n' '.' <$FILE )

arr=$(echo $temp | tr "." "\n")

for x in $arr
do
    echo "$x"
done

所有这一切都是在一行上打印出每个单词。现在我需要计算每个单词出现的次数,然后在单词旁边打印出来。例如:

临时内容=苹果,梨,苹果,桃子

输出应该是:

apple 2
pear 1
apple 2
peach 1

每个单词都在一个新行上。

4

2 回答 2

1

uniq(1)大概可以做你想做的事。例如:

$ echo 'foo.bar.baz.bar.foo.box.foo' | tr '.' '\n' | sort | uniq -c
      2 bar
      1 baz
      1 box
      3 foo
$

请注意,uniq需要排序输入才能正确计算出现次数。

于 2013-02-07T03:12:42.943 回答
1

您可以在 awk 中执行此操作。给定一个看起来像这样的文件:

this.is.a.test
and.this.is.test2
and.this.is.test3

以下 awk 将为您提供单词及其计数

awk 'BEGIN{
        FS="."
    }
    {
        for(i=1;i<=NF;i++){
            a[$i]++
        }
    } 
    END{ 
        for(word in a)print word, a[word]
    }'

将产生以下输出:

test 1
a 1
test2 1
test3 1
and 2
this 3
is 3
于 2013-02-07T03:13:27.740 回答