并排显示两个文件

Chr*_*our 86 unix linux shell command-line gnu-coreutils

不同长度的2个未排序文本文件如何可以是由侧显示侧(在列)在一个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
Run Code Online (Sandbox Code Playgroud)

显示:

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

                                    skipped a line
Run Code Online (Sandbox Code Playgroud)

paste one.txt two.txt几乎没有诀窍,但没有很好地对齐列,因为它只是在第1列和第2列之间打印一个选项卡.我知道如何使用emacs和vim,但希望输出显示为stdout用于管道等.

我提出的解决方案使用sdiff然后管道sed删除输出sdiff添加.

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

我可以创建一个函数并将其粘贴在我的.bashrc但是肯定已经存在的命令(或者可能是更清洁的解决方案)?

Has*_*kun 154

您可以使用pr要做到这一点,使用-m标志合并文件,每列一个,而-t忽略标题,例如.

pr -m -t one.txt two.txt
Run Code Online (Sandbox Code Playgroud)

输出:

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

                                    skipped a line
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 完善!知道什么会存在,从来没有听说过'pr`.我尝试了3个文件,输出被截断,但`-w`选项解决了这个问题.很好的答案. (14认同)
  • @sudo_o:很乐意提供帮助,coreutils充满了宝石 (5认同)
  • 很棒的-w WIDTH选项有助于格式化它. (4认同)
  • @Matt:您可以使用`$ COLUMNS`,它应该由shell提供. (2认同)

pva*_*erk 30

为了扩展@Hasturkun的答案:默认情况下pr,它的输出仅使用72列,但使用终端窗口的所有可用列相对容易:

pr -w $COLUMNS -m -t one.txt two.txt
Run Code Online (Sandbox Code Playgroud)

大多数shell将在环境变量中存储(并更新)终端的screenwidth $COLUMNS,因此我们只是将该值传递pr给用于其输出的宽度设置.

这也回答了@Matt的问题:

pr有自动检测屏幕宽度的方法吗?

所以,不:pr本身无法检测到屏幕宽度,但我们通过-w选项传递终端的宽度来帮助我们.


Bar*_*mar 6

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])}
}'
Run Code Online (Sandbox Code Playgroud)

使用*的格式规范允许你动态地提供字段长度.


小智 5

如果您想知道两个并排文件之间的实际差异,请使用diff -y

diff -y file1.cf file2.cf
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下选项设置输出宽度-W, --width=NUM

diff -y -W 150 file1.cf file2.cf
Run Code Online (Sandbox Code Playgroud)

并使diff的列输出适合您当前的终端窗口:

diff -y -W $COLUMNS file1.cf file2.cf
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你知道输入文件没有标签,那么使用expand简化@oyss答案:

paste one.txt two.txt | expand --tabs=50
Run Code Online (Sandbox Code Playgroud)

如果输入文件中可能有选项卡,则可以先扩展:

paste <(expand one.txt) <(expand two.txt) | expand --tabs=50
Run Code Online (Sandbox Code Playgroud)