我需要找到目录中每个文件最常见的单词并按如下方式打印:
12 my /home/test/file1.txt
5 you /home/test/file3.txt
7 hello /home/test/file4.txt
我试过:
for tmp in <path>
do
tr -c '[:alnum:]' '[\n*]' < "$tmp" | sort | uniq -c | sort -nr | head -1
done
这不起作用
答案1
我将使用grep
with-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
或者,如果您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