【问题标题】:Vertical alignment of lists with different content in bashbash中具有不同内容的列表的垂直对齐
【发布时间】:2016-12-19 15:48:17
【问题描述】:

假设两个列表具有不同的内容。为简单起见,我们假设这些列表仅包含字母数字字符串。我想合并并垂直对齐bash 中的两个列表。

user$ cat file1
foo
foo
bar
qux

user$ cat file2
foo
bar
bar
baz
qux

user$ sought_command file1 file2
foo foo
foo -
bar bar
- bar
- baz
qux qux

每行值之间的分隔符(此处为单个空格)不需要由用户选择,但可以硬编码。间隙的占位符也可以(这里是破折号)。

编辑:

理想情况下,此命令不限于两个输入列表,而是可以采用任意数量的输入文件,每个文件都与指定的第一个文件进行比较。

user$ sought_command file1 file2 file2
foo foo foo
foo - -
bar bar bar
- bar bar
- baz baz
qux qux qux

【问题讨论】:

  • 乍一看,comm 可能是您需要的工具。您需要对输出进行后处理以正确翻译缺失的字段。但是,它需要排序的输入,因此它可能不是适合这项工作的工具,除非输出的顺序无关紧要。几乎可以肯定,需要awk(或 Perl 或 Python,或……)。由于您的内容匹配要求,您不能使用paste。使用超过 2 个文件执行此操作会使 Perl 或 Python 比 awk 更合适,但如果您真的很努力,您可能可以在 awk 中执行此操作。
  • 哪个版本的 bash?
  • @cdarke 理想情况下,该代码适用于 GNU bash 4.3.46
  • diff -u 的输出也可以作为一个有用的起点,但您需要对其进行后期处理。

标签: string bash command-line text-alignment


【解决方案1】:

这是 Ohad Eytan 答案的一个很可能更快的版本,仅与超大或很多文件相关:

diff -t -y file1 file2 | tr -s ' ' | tr '[<>]' '-' | grep -o '\S\+ \S\+'

【讨论】:

    【解决方案2】:

    仅比较两个文件时,diffsed 将起作用

    diff -y file1 file2 | sed 's/[[:space:]]\+/ /g' | sed 's/[<,>]/- /g'
    

    结果(排列整齐):

    foo foo
    foo -
    bar bar
     -  bar
     -  baz
    qux qux
    

    需要做更多工作才能处理大于 2 的输入文件。

    【讨论】:

    • 我们甚至没有获得替代解决方案的支持? ;-(
    【解决方案3】:

    您可以使用diff-y 标志来获取:

    $ diff -y file1 file2
    foo                             foo
    foo                               <
    bar                             bar
                                      > bar
                                      > baz
    qux                             qux
    

    trsed一起:

    $ diff -t -y file1 file2 | tr -s ' ' | sed 's/[<>]/-/' 
    foo foo
    foo -
    bar bar
     - bar
     - baz
    qux qux
    

    【讨论】:

    • @OhadEytan 很好的答案!谢谢。
    猜你喜欢
    • 2014-08-03
    • 1970-01-01
    • 2013-09-11
    • 2016-10-19
    • 1970-01-01
    • 2012-08-28
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多