bash脚本显示读取文件时的行号
我有一个bash脚本,它将两个文件作为命令行输入,并检查它们是否是同一个文件 我试图增强我的脚本,这样当它确定两个文件是否不同时,它也会显示上次读取的行号。有没有一种方法可以做到这一点,而不只是在循环中创建一个计数器 我现在得到的是:bash脚本显示读取文件时的行号,bash,file-io,Bash,File Io,我有一个bash脚本,它将两个文件作为命令行输入,并检查它们是否是同一个文件 我试图增强我的脚本,这样当它确定两个文件是否不同时,它也会显示上次读取的行号。有没有一种方法可以做到这一点,而不只是在循环中创建一个计数器 我现在得到的是: while read line1 0<&3 do if read line2 0<&4 then # if line are different, the two files are not th
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
读取第10行时没有计数器?…这很遗憾,因为这是最有效的方法…但是,这里对代码进行了一个非常小的更改,使其显示行号而不使用计数器:
#!/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
#/bin/bash
除非你有真正的理由,否则我会继续使用现有的工具man diff
将向您展示如何准确地执行您正在尝试的操作,但有一些选项。Ummm,为什么不使用diff命令?请尝试diff file1 file2
^,diff file1 file2
Soo什么echo diff file1 file2
?我对那个司令部一无所知你说的是我输出的整个格式。。这只是因为在我猜之前我就是这样拥有它的。这正是我一直在寻找的。谢谢我想我更喜欢cmp
,cmp
的输出在他的情况下更容易解析/符合他的要求,cmp
将是另一个不错的选择。