linux - 查找包含另一个文件中所有单词/行的所有文件

标签 linux bash awk sed grep

我要直接说这是一个家庭作业问题,但我觉得我已经用尽了所有与如何解决此问题相关的在线搜索,或者我只是没有正确地为 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/

相关文章:

linux - Windows 操作系统使用哪种语言进行编码?

linux - 当 while/if/etc 出现错误时如何使 bash 脚本失败?

awk - 如何使用 awk 每 n 行插入一个空行?

linux - 我可以使用 unix utils 以编程方式将 "burn in"ANSI 控制代码写入文件吗?

linux - gnuplot 线型不想改变

Linux:如何将安装目录移动到其他地方?

linux - 如何在 Linux 上构建 BlackBerry 应用程序?

linux - 解压缩连接两个 gzip 文件的结果是否总是等于以原始和解压缩形式连接两个文件的结果?

bash - Sed 无法更新长文本

linux - awk 将值与输入进行比较