并排显示两个文件

如何将两个未sorting的不同长度的文本文件并排显示在一个shell (列)

给定one.txttwo.txt

 $ cat one.txt apple pear longer line than the last two last line $ cat two.txt The quick brown fox.. foo bar linux skipped a line 

显示:

 apple The quick brown fox.. pear foo longer line than the last two bar last line linux skipped a line 

paste one.txt two.txt几乎做的伎俩,但没有很好地alignment列,因为它只是列1和2之间打印一个选项卡。 我知道如何与emacs和vim,但希望输出显示为标准输出pipe道等。

我提出的解决scheme使用sdiff ,然后pipe道sed删除输出sdiff添加。

sdiff one.txt two.txt | sed -r 's/[<>|]//;s/(\t){3}//'

我可以创build一个函数并将其粘贴到我的.bashrc但是肯定已经有一个命令存在(或者是一个更清晰的解决scheme)?

您可以使用pr来执行此操作,使用-m标志合并文件,每列一个, -t省略标题,例如。

 pr -m -t one.txt two.txt 

输出:

 apple The quick brown fox.. pear foo longer line than the last two bar last line linux skipped a line 

在@Hasturkun的答案上稍微扩展一下:默认情况下, pr只使用72列作为输出,但使用terminal窗口的所有可用列相对容易:

 pr -w $COLUMNS -m -t one.txt two.txt 

大多数shell将在$COLUMNS环境variables中存储(和更新)terminal的屏幕宽度,所以我们只是将该值传递给pr来使用其输出的宽度设置。

这也回答@Matt的问题:

有没有一种方法可以自动检测屏幕宽度?

所以,no: pr本身无法检测到屏幕宽度,但是我们通过-w选项传递terminal宽度来帮助我们。

 paste one.txt two.txt | awk -F'\t' '{ if (length($1)>max1) {max1=length($1)}; col1[NR] = $1; col2[NR] = $2 } END {for (i = 1; i<=NR; i++) {printf ("%-*s %s\n", max1, col1[i], col2[i])} }' 

在格式规范中使用*可以让您dynamic地提供字段长度。

如果你知道input文件没有选项卡,那么使用expand简化了@oyss的答案 :

 paste one.txt two.txt | expand --tabs=50 

如果input文件中可能有选项卡,则可以始终首先展开:

 paste <(expand one.txt) <(expand two.txt) | expand --tabs=50 

从Barmar的答案中删除dynamic字段长度计数将使它更短的命令….但是你仍然需要至less一个脚本来完成无论你select什么方法都无法避免的工作。

 paste one.txt two.txt |awk -F'\t' '{printf("%-50s %s\n",$1,$2)}' 

有一个sed方式:

 f1width=$(wc -L <one.txt) f1blank="$(printf "%${f1width}s" "")" paste one.txt two.txt | sed " s/^\(.*\)\t/\1$f1blank\t/; s/^\(.\{$f1width\}\) *\t/\1 /; " 

(当然@Hasturkun的解决scheme是最准确的 !)

 diff -y <file1> <file2> [root /]# cat /one.txt 
苹果
梨
比上两次更长
最后一行
 [root /]# cat /two.txt 
快速的棕色狐狸
 FOO
酒吧
 Linux的
 [root@RHEL6-64 /]# diff -y one.txt two.txt 
苹果| 快速的棕色狐狸
梨|  FOO
比最后两个|更长的行 酒吧
最后一行|  Linux的

如果你想知道两个文件的实际区别,请使用下面的命令

 diff -y file1.cf file2.cf 

您也可以使用-W, --width=NUM选项来设置宽度以打印列:

 diff -y -W 150 file1.cf file2.cf 

下面find一个基于python的解决scheme。

 import sys # Specify the number of spaces between the columns S = 4 # Read the first file l0 = open( sys.argv[1] ).read().split('\n') # Read the second file l1 = open( sys.argv[2] ).read().split('\n') # Find the length of the longest line of the first file n = len(max(l0, key=len)) # Print the lines for i in xrange( max( len(l0), len(l1) ) ): try: print l0[i] + ' '*( n - len(l0[i]) + S) + l1[i] except: try: print ' ' + ' '*( n - 1 + S) + l1[i] except: print l0[i] 

 apple The quick brown fox.. pear foo longer line than the last two bar last line linux skipped a line