gpt4 book ai didi

linux - 如何检查一个文件是否是另一个文件的一部分?

转载 作者:IT王子 更新时间:2023-10-29 00:13:15 26 4
gpt4 key购买 nike

我需要通过 bash 脚本检查一个文件是否在另一个文件中。对于给定的多行模式和输入文件。

返回值:

我想接收状态(如何在 grep 命令中)如果找到任何匹配项,则为 0,如果未找到匹配项,则为 1。

图案:

  • 多行
  • 行的顺序很重要(被视为单个行 block ),
  • 包括数字、字母、?、&、*、#等字符,

解释

只有以下示例才能找到匹配项:

pattern     file1 file2 file3 file4
222 111 111 222 222
333 222 222 333 333
333 333 444
444

以下不应该:

pattern     file1 file2 file3 file4 file5 file6 file7
222 111 111 333 *222 111 111 222
333 *222 222 222 *333 222 222
333 333* 444 111 333
444 333 333

这是我的脚本:

#!/bin/bash

function writeToFile {
if [ -w "$1" ] ; then
echo "$2" >> "$1"
else
echo -e "$2" | sudo tee -a "$1" > /dev/null
fi
}

function writeOnceToFile {
pcregrep --color -M "$2" "$1"
#echo $?

if [ $? -eq 0 ]; then
echo This file contains text that was added previously
else
writeToFile "$1" "$2"
fi
}

file=file.txt
#1?1
#2?2
#3?3
#4?4

pattern=`cat pattern.txt`
#2?2
#3?3

writeOnceToFile "$file" "$pattern"

我可以对所有模式行使用 grep 命令,但在这个例子中它失败了:

file.txt 
#1?1
#2?2
#=== added line
#3?3
#4?4

pattern.txt
#2?2
#3?3

或者即使你换行:2 和 3

file=file.txt 
#1?1
#3?3
#2?2
#4?4

在不应该的时候返回 0。

我该如何解决?请注意,我更喜欢使用 native 安装的程序(如果可以不用 pcregrep)。也许 sed 或 awk 可以解决这个问题?

最佳答案

我将只使用 diff 来完成这个任务:

diff pattern <(grep -f file pattern)

说明

  • diff file1 file2 报告两个文件是否不同。

  • 通过说 grep -f file pattern,您可以看到 pattern 的内容在 file 中。

因此,您正在做的是检查 pattern 中的哪些行在 file 中,然后将其与 pattern 本身进行比较。如果它们匹配,则意味着 patternfile 的子集!

测试

seq 10seq 20 的一部分!让我们检查一下:

$ diff <(seq 10) <(grep -f <(seq 20) <(seq 10))
$

seq 10 不在 seq 2 20 中(1 不在第二个中):

$ diff -q <(seq 10) <(grep -f <(seq 2 20) <(seq 10))
Files /dev/fd/63 and /dev/fd/62 differ

关于linux - 如何检查一个文件是否是另一个文件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31540902/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com