我需要一个简单的 shell 程序,它必须执行如下操作:
script.sh word_to_find file1 file2 file3 .... fileN
将显示
word_to_find 3 - if word_to_find appears in 3 files
或
word_to_find 5 - if word_to_find appears in 5 files
这是我试过的
#!/bin/bash
count=0
for i in $@; do
if [ grep '$1' $i ];then
((count++))
fi
done
echo "$1 $count"
但是这个消息出现了:
syntax error: "then" unexpected (expecting "done").
在此之前错误是
[: grep: unexpected operator.
最佳答案
试试这个:
#!/bin/sh
printf '%s %d\n' "$1" $(grep -hm1 "$@" | wc -l)
注意脚本的所有参数是如何逐字传递给 grep
的——第一个是搜索表达式,其余是文件名。
grep -hm1
的输出是一个匹配列表,每个文件一个匹配,wc -l
对它们进行计数。
我最初使用 grep -l
发布了这个答案,但是这要求文件名永远不包含换行符,这是一个相当讨厌的限制。
如果不需要正则表达式搜索(即只搜索文字文本),可以添加一个 -F
选项。
关于linux - 用于在文件列表中查找单词的 shell 脚本,所有文件都作为参数给出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322577/