bash 文本搜索:查找一个文件的内容是否存在于另一个文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21128592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:15:24  来源:igfitidea点击:

bash text search: find if the content of one file exists in another file

bashshell

提问by Abathur

Say we have two files: a.txt and b.txt. Each file has multiple lines of text.

假设我们有两个文件:a.txt 和 b.txt。每个文件都有多行文本。

How do I write a shell script to check if all of the content of a.txt exists in b.txt?

如何编写 shell 脚本来检查 a.txt 的所有内容是否都存在于 b.txt 中?



Thx for the hints guys, i didn't noticed -q will output 0 if successfully matched.

感谢提示家伙,我没有注意到 -q 如果成功匹配将输出 0。

I end up with:

我最终得到:

if grep a.txt -q -f b.txt; then

如果grep a.txt -q -f b.txt; 然后

else

别的

fi

回答by orange

try grep

尝试 grep

cat b.txt|grep -f a.txt

回答by BMW

Using grep

使用 grep

grep -f a.txt b.txt

回答by csiu

Here is a script that will do what what you are describing:

这是一个脚本,它将执行您所描述的操作:

run: sh SCRIPT.sh a.txt b.txt

跑: sh SCRIPT.sh a.txt b.txt

# USAGE:   sh SCRIPT.sh TEST_FILE CHECK_FILE
TEST_FILE=
CHECK_FILE=

## for each line in TEST_FILE
while read line ; do

    ## check if line exist in CHECK_FILE; then assign result to variable
    X=$(grep "^${line}$" ${CHECK_FILE})


    ## if variable is blank (meaning TEST_FILE line not found in CHECK_FILE)
    ## print 'false' and exit
    if [[ -z $X ]] ; then
        echo "false"
        exit
    fi

done < ${TEST_FILE}

## if script does not exit after going through each line in TEST_FILE,
## then script will print true
echo "true"

Assumptions:

假设:

  • line order from a.txtdoes not matter
  • a.txt中的行顺序无关紧要

回答by GreenAsJade

You need to write a loop that iterates over each line in a.txt and use grep (or some other means) to see if that line is in b.txt. If you find any instance where it is notin b.txt, then you can provide the answer: not all lines match. If you find no such instances, you can conclude that all lines match.

您需要编写一个循环来遍历 a.txt 中的每一行,并使用 grep(或其他方法)查看该行是否在 b.txt 中。如果您发现它不在b.txt 中的任何实例,那么您可以提供答案:并非所有行都匹配。如果未发现此类实例,则可以得出所有行都匹配的结论。

Capturing the output of grep using backticks would likely be useful:

使用反引号捕获 grep 的输出可能会很有用:

if [`grep -v $line b.txt`==  ""]; then

kind of thing.

之类的事情。

If you have specific questions about how to iterate over the contents of a file, you should ask a specific question about that, showing what you tried.

如果您有关于如何迭代文件内容的特定问题,您应该提出一个关于此的特定问题,显示您尝试过的内容。