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



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

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


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

我最终得到:

如果grep a.txt -q -f b.txt ; 则

fi

尝试grep

cat b.txt|grep -f a.txt

使用 grep

grep -f a.txt b.txt

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

运行: sh SCRIPT.sh a.txt b.txt

# USAGE:   sh SCRIPT.sh TEST_FILE CHECK_FILE
TEST_FILE=$1
CHECK_FILE=$2
## 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"

假设:

  • 来自 A.txt 的行顺序无关紧要

你需要编写一个循环来迭代a.txt中的每一行,并使用grep(或其他一些方法)来查看该行是否在b.txt中。 如果您发现任何不在 b.txt 中的实例,那么您可以提供答案:并非所有行都匹配。 如果没有找到此类实例,则可以断定所有行都匹配。

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

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

之类的事情。

如果您对如何迭代文件的内容有具体问题,您应该就此提出一个特定问题,展示您尝试过的内容。

最新更新