用于确定文件中出现哪些字符的命令

时间:2012-11-08 15:03:34

标签: linux file character

我正在寻找一个Linux / UNIX命令来确定文件中的不同字符。字符数很好,但不是必需的。例如,如果我在包含此数据的文件上运行命令...

This is
my data
file.

......它会给我这个输出......

T h i s m y d a t f l e .

......甚至更好,这个。

T:1 h:1 i:3 s:2 m:1 y:1 d:1 a:2 t:1 f:1 l:1 e:1 .:1

在输出中,字符的顺序无关紧要,它们是否用空格,制表符,线等分隔也不重要。

2 个答案:

答案 0 :(得分:2)

要打印唯一字符:

$ grep -o . file | sort -u | tr -d '\n'
 .Tadefhilmsty

计算每个字符的出现次数:

$ grep -o . file | sort | uniq -c
      2
      1 .
      1 T
      2 a
      1 d
      1 e
      1 f
      1 h
      3 i
      1 l
      1 m
      2 s
      1 t
      1 y

我会把格式留给你。

答案 1 :(得分:1)

我不知道有任何unix命令可以做到这一点,但是可以通过一个小的python脚本得到你想要的东西

#!/usr/bin/env python

import collections, sys
d = collections.defaultdict(int)
for line in sys.stdin:
    for c in line:
        d[c] += 1
print dict(d)

将给出结果

{'a': 2, ' ': 2, 'e': 1, 'd': 1, 'f': 1, 'i': 3, 'h': 1, '\n': 2, 'm': 1, 'l': 1, '.': 1, 's': 2, 'T': 1, 'y': 1, 't': 1}