我要直接说这是一个家庭作业问题,但我觉得我已经用尽了所有与如何解决此问题相关的在线搜索,或者我只是没有正确地为 Google/堆栈溢出。
问题是这样开始的:文件words包含一个单词列表。每个单词都占单独的一行。文件story1、story2、...、story100是短篇小说。
这是一个由多部分组成的问题,但最后一部分难倒了我:找出包含文件 words. 中所有单词的故事文件
之前有一个类似的问题:找出文件中至少包含一个单词的故事文件(打印文件名)单词。
我用 grep 解决了这个问题:
grep -l -f words story*
我的印象是我还必须使用 grep 来解决最后一个问题,但我似乎找不到 grep 的选项或任何只返回与模式文件中的所有内容匹配的文件的选项。看来我可能必须使用 shell 脚本来完成此操作,但不确定从哪里开始,或者是否需要 grep 来完成此操作。有关如何解决此问题的任何指示吗?
谢谢!
编辑:
这些是讲师给我们的解决方案中的正确答案。
主要问题之前的问题: grep -l -f Words Story*
主要问题:
for story in `ls story*`
do
(( match = 0 ))
for word in `cat words`
do
if [ `grep -l $word $story` ]
then
(( match++ ))
else
break
fi
done
if [ $match -eq `wc -w < words` ]
then
echo $story
fi
done
感谢大家深思熟虑的意见和答案,抱歉我有点晚了。
最佳答案
# wcheck: finds story* files that contain all words in words file
# for each file named story... (in this directory)
for file in story*
do
stGood=0 # story is intialized as containing words or true
## for each word in the words file
for word in $(cat words) ; do
## if test using grep exit status for existance of word
if ! grep -q -F $word $file
then
stGood=1 #if word is not found story is set to false
break
fi
done
## if story is still true then filename is printed
if [ $stGood == 0 ]
then
echo $file
fi
done
exit
关于linux - 查找包含另一个文件中所有单词/行的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006575/