如何在unix中打印文件中某个单词的出现次数
How to print number of occurances of a word in a file in unix
这是我的 shell 脚本。
给定一个目录和一个单词,搜索该目录并打印该单词出现次数最多的文件的绝对路径,并打印出现次数。
我写了下面的脚本
#!/bin/bash
if [[ -n $(find / -type d -name 2> /dev/null) ]]
then
echo "Directory exists"
x=` echo " $(find / -type d -name 2> /dev/null)"`
echo "$x"
cd $x
y=$(find . -type f | xargs grep -c | grep -v ":0"| grep -o '[^/]*$' | sort -t: -k2,1 -n -r )
echo "$y"
else
echo "Directory does does not exists"
fi
result: scriptname directoryname word
output: /somedirectory/vtb/wordsearch : 4
/foo/bar: 3
是否有替代 xargs grep -c $2 的选项?因为 grep -c 打印包含单词的行数,但我需要打印给定目录中文件中单词的确切出现次数
grep -Fwor "$word" "$dir" | sed "s/:${word}$//" | sort | uniq -c | sort -n | tail -1
试试这个:
grep -o -w 'foo' bar.txt | wc -w
或
grep -o -w 'word' /path/to/file/ | wc -w
使用 grep 的 -c
计数功能:
grep -c "SEARCH" /path/to/files* | sort -r -t : -k 2 | head -n 1
grep 命令将以 /path/name:count
格式输出每个文件,排序将按数字 (-n
) 由冒号分隔的第二个 (-k 2
) 字段排序 ( -t :
) 以相反的顺序 (-r
)。然后我们使用 head 来保留第一个结果 (-n 1
).
这是我的 shell 脚本。 给定一个目录和一个单词,搜索该目录并打印该单词出现次数最多的文件的绝对路径,并打印出现次数。 我写了下面的脚本
#!/bin/bash
if [[ -n $(find / -type d -name 2> /dev/null) ]]
then
echo "Directory exists"
x=` echo " $(find / -type d -name 2> /dev/null)"`
echo "$x"
cd $x
y=$(find . -type f | xargs grep -c | grep -v ":0"| grep -o '[^/]*$' | sort -t: -k2,1 -n -r )
echo "$y"
else
echo "Directory does does not exists"
fi
result: scriptname directoryname word
output: /somedirectory/vtb/wordsearch : 4
/foo/bar: 3
是否有替代 xargs grep -c $2 的选项?因为 grep -c 打印包含单词的行数,但我需要打印给定目录中文件中单词的确切出现次数
grep -Fwor "$word" "$dir" | sed "s/:${word}$//" | sort | uniq -c | sort -n | tail -1
试试这个:
grep -o -w 'foo' bar.txt | wc -w
或
grep -o -w 'word' /path/to/file/ | wc -w
使用 grep 的 -c
计数功能:
grep -c "SEARCH" /path/to/files* | sort -r -t : -k 2 | head -n 1
grep 命令将以 /path/name:count
格式输出每个文件,排序将按数字 (-n
) 由冒号分隔的第二个 (-k 2
) 字段排序 ( -t :
) 以相反的顺序 (-r
)。然后我们使用 head 来保留第一个结果 (-n 1
).