我有一个bash脚本,它将两个文件作为命令行输入,并检查它们是否是同一个文件。
我正在尝试增强我的脚本,以便在确定两个文件是否不同时,它还会显示上次读取的行号。有没有办法在没有在循环中制作计数器的情况下做到这一点?
我现在得到了什么:
while read line1 0<&3
do
if read line2 0<&4
then
# if line are different, the two files are not the same
if [ "$line1" != "$line2" ]
then
echo "$1 and $2 are different"
echo " $1: $line1"
echo " $2: $line2"
exit 1
fi
else
# if EOF for file2 is reached then file1 is bigger than file2
echo "$1 and $2 are different and $1 is bigger than $2."
exit 1
fi
done
它会打印正在检查的文件中的包含行,但不会打印行号吗?有什么提示吗?
答案 0 :(得分:2)
没有反击?...这是一个遗憾,因为这是最有效的方式......但是,这是对您的代码进行的一个非常小的更改,使其在不使用计数器的情况下显示亚麻布:
#!/bin/bash
exec 3< <( grep -n "" $1 )
exec 4< <( grep -n "" $2 )
while read line1 <&3
do
if read line2 <&4
then
# if line are different, the two files are not the same
if [ "$line1" != "$line2" ]
then
echo "$1 and $2 are different"
echo " $1: $line1"
echo " $2: $line2"
exit 1
fi
else
# if EOF for file2 is reached then file1 is bigger than file2
echo "$1 and $2 are different and $1 is bigger than $2."
exit 1
fi
done
答案 1 :(得分:0)
除非你有真正的理由,否则我会继续使用现有的工具。 man diff
将向您展示如何完成您正在尝试的内容,但有选项。