我正在寻找一个 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
在输出中,字符的顺序无关紧要,它们是否用空格、制表符、行等分隔也无关紧要。
要打印唯一字符:
$ 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
我会把格式留给你。
我不知道有任何 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}