Mor*_*123 5 bash text-processing files
我需要在一个目录中找到每个文件中最常用的词,然后像这样打印:
12 my /home/test/file1.txt
5 you /home/test/file3.txt
7 hello /home/test/file4.txt
Run Code Online (Sandbox Code Playgroud)
我试过:
for tmp in <path>
do
tr -c '[:alnum:]' '[\n*]' < "$tmp" | sort | uniq -c | sort -nr | head -1
done
Run Code Online (Sandbox Code Playgroud)
它不起作用
我将使用grepwith-o仅打印匹配的字符串顶部提取单词:
$ for file in *; do
printf '%s : %s\n' "$(grep -Eo '[[:alnum:]]+' "$file" | sort | uniq -c |
sort -rn | head -n1)" "$file"
done
8 no : file1
10 so : file2
12 in : file3
Run Code Online (Sandbox Code Playgroud)
或者,如果您grep不支持-o,您可以使用tr来替换所有空格和标点符号\n,过滤grep .以跳过空白行,然后进行计数:
$ for file in *; do
printf '%s : %s\n' "$(tr '[[:punct:]][[:space:]]' '\n' < "$file" | grep . |
sort | uniq -c | sort -rn | head -n1)" "$file"
done
8 no : file1
10 so : file2
12 in : file3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1295 次 |
| 最近记录: |