我是 Unix Shell 脚本新手。我需要编写一个 shell 脚本来比较 2 个 sql 输出文件(基本上为 .txt 格式),它们是同一 sql 查询的输出(在克隆等维护任务之前和之后),并将差异打印到另一个文本文件中。
输出文件 1(克隆之前):
NAME OPEN_MODE
--------- ----------
PROD123 READ WRITE
输出文件2(克隆后):
NAME OPEN_MODE
--------- ----------
DEV123 READ WRITE
我们需要比较上面两个输出文件,并根据差异将差异打印到另一个文本文件中。例如:
在上面的输出中,“NAME”列值不匹配。因此,差异应该打印到另一个文件中,如下所示:
名称不匹配。 OPEN_MODE 匹配。请检查。
并且输出文件将具有多个这样的输出。因此,我们还需要检查所有这些输出并将差异假脱机到另一个文件。任何能够实现相同目的的示例 shell 脚本都会有所帮助。
问候, AR
答案1
这是使用 awk 的解决方案:
#!/usr/bin/awk -f
NR == 1 {
# Get the headers on the first line.
# Will be done for both files, but we don't mind.
head[1] = $1;
head[2] = $2;
}
NR == 3 {
# For the third line, go though the data in both columns...
for (i = 1; i <= 2; ++i) {
# If there's something in col[], then this is the second file.
if (col[i]) {
# This is the second file.
# Test the value of the column against what was in the first file.
if (col[i] == $i) {
printf("%s is matching. ", head[i]);
} else {
printf("%s is not matching. ", head[i]);
# Flag that we need to print extra info later.
check = 1;
}
} else {
# This is the first file.
# Remember the data in the two columns.
col[1] = $1;
col[2] = $2;
# Reset the record (line) counter.
NR = 0;
# Skip to the second file.
nextfile;
}
}
if (check) {
printf("Please check.");
}
printf("\n");
}
测试它:
$ ./script.awk file1 file2
NAME is not matching. OPEN_MODE is matching. Please check.
答案2
使用差异
diff file1 file2 > changes.log