【发布时间】:2015-10-11 00:23:28
【问题描述】:
我需要通过 bash 脚本检查一个文件是否在另一个文件中。对于给定的多行模式和输入文件。
返回值:
我想接收状态(如何在 grep 命令中)如果找到任何匹配项,则为 0,如果未找到匹配项,则为 1。
模式:
- 多行,
- 行的顺序很重要(被视为单个行),
- 包括数字、字母、?、&、*、# 等字符,
说明
只有以下示例应该找到匹配项:
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。
我该如何解决?请注意,我更喜欢使用本机安装程序(如果可以不使用 pcregrep)。也许 sed 或 awk 可以解决这个问题?
【问题讨论】:
-
您是想查明文件中是否已经存在任何给定行,或者整个新行集是否已经作为单个行块存在于文件中?
-
我想检查输入文件中是否存在完整模式(作为单个行块)。
-
您可能需要更新您的问题,以便更早地说明这与忽略换行符的子字符串匹配略有不同。因为正如您的
...\n*222\n333\n...不匹配大小写所示,您需要对块进行模式匹配以从行首开始匹配,并在行尾结束。
标签: linux bash command-line pcregrep