我想在 AIX 中比较 2 个文件并打印数字差异

我想在 AIX 中比较 2 个文件并打印数字差异

我想比较 2 个文件,例如file1file2,并且在输出中我必须打印差异以及添加和/或删除了多少行。

文件1

apple1
apple2
apple3
apple4

文件2

apple1
apple2
apple3
apple4
grape1
grape2
grape3
mango4

输出应该是:

No of newly added list= 4
No of lines removed =0
Difference =4 

Newely Added list 
------------

grape1
grape2
grape3
mango4

Removed list 
--------
None

答案1

如果您不需要确切的输出格式,您可以使用diffdiffstat

例如

$ diff file1 file2 | diffstat -s
 1 file changed, 4 insertions(+)

比如说,如果apple4从 中删除file2,输出将如下所示:

$ diff file1 file2 | diffstat -s
 1 file changed, 4 insertions(+), 1 deletion(-)

如果您确实需要确切的输出,您可以diff在脚本中单独使用,如下所示:

#! /bin/sh

if [ ! "$#" -eq 2 ] ; then
  echo "Exactly two file arguments are required."
  exit 1
fi

f1="$1"
f2="$2"    

# sort and uniq the input files before diffing.
# if you have `mktemp`, use this:
t1=$(mktemp)
t2=$(mktemp)
# else kludge it with something like this:
# mkdir ~/tmp
# t1="~/tmp/$f1.tmp"
# t2="~/tmp/$f2.tmp"

# if your `sort` has a `-u` option for `uniq` (e.g. GNU sort), you
# can use `sort -u` instead of `sort | uniq`
sort "$f1" | uniq > "$t1"
sort "$f2" | uniq > "$t2"

add=$(diff "$t1" "$t2" | grep -c '^> ')
del=$(diff "$t1" "$t2" | grep -c '^< ')

[ -z "$add" ] && add=0
[ -z "$del" ] && del=0

diff=$(( add - del ))

cat <<__EOF__
No of newly added list= $add
No of lines removed = $del
Difference = $diff

Newly Added list 
------------
__EOF__

if [ "$add" -eq 0 ] ; then
   echo None.
else
  diff "$t1" "$t2" | sed -n -e 's/^> //p'
fi

cat <<__EOF__

Removed list 
--------
__EOF__

if [ "$del" -eq 0 ] ; then
   echo None.
else
  diff "$t1" "$t2" | sed -n -e 's/^< //p'
fi

rm -f "$t1" "$t2"

如果您grep没有-c选项,请使用diff ... | grep ... | wc -l

如果您没有内置的整数运算,您可以使用bcordc或其他东西来进行计算。sh我不记得有任何不这样做的,但商业 UNIX 可以有一些非常原始和古老的常用工具的实现。该脚本已经过测试,dash因此应该适用于任何当前的 POSIX shell。

输出:

$ ./keerthana.sh file1 file2
No of newly added list = 4
No of lines removed = 0
Difference = 4

Newly Added list 
------------
grape1
grape2
grape3
mango4

Removed list 
--------
None.

相关内容