【问题标题】:Align text by string using shell commands使用 shell 命令按字符串对齐文本
【发布时间】:2014-02-09 04:21:10
【问题描述】:

假设我在这样的文件中有一些文本:

lorem ipsum asdf gh 12345
hello, world! asdf gh this is a test
ee asdf gh ii

请注意,每一行都包含“asdf gh”。我希望能够使用一些 shell 命令来根据该分隔符字符串对齐该文本,所以我可以这样做:

$ cat my-file | some-command
lorem ipsum     asdf gh   12345
hello, world!   asdf gh   this is a test
ee              asdf gh   ii

在此示例中,我在分隔符周围添加了额外的空格,但这并不重要。也就是说,输出也可以是:

$ cat my-file | some-command
lorem ipsum   asdf gh 12345
hello, world! asdf gh this is a test
ee            asdf gh ii

有没有简单的方法来做到这一点?我知道column 可以分栏,但它只能使用空格或字符(不是字符串或模式)作为分隔符。

【问题讨论】:

    标签: regex shell awk sed printf


    【解决方案1】:

    awk 是一个更好的格式化输出的工具:

    awk -F 'asdf gh' '{printf "%-15s%-10s%-10s\n", $1, FS, $2}'  file
    lorem ipsum    asdf gh    12345    
    hello, world!  asdf gh    this is a test
    ee             asdf gh    ii    
    

    您可以更改printf 中的数字以进行更多自定义。

    【讨论】:

      【解决方案2】:

      在 awk 中使用 printf 函数

      awk '{printf "%-20s%s\t%s\n",$1,FS,$2}' FS="asdf gh" file
      
      lorem ipsum         asdf gh  12345
      hello, world!       asdf gh  this is a test
      ee                  asdf gh  ii
      

      【讨论】:

        【解决方案3】:

        除非您想使用 awk 并且遇到两个问题,否则您可以按照以下方式进行:

        sed 's/asdf gh/%&/g' <my-file | column -t -s'%'
        

        假设 '%' 是一个不会出现在文本中的有效分隔符。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-24
          • 2015-11-21
          相关资源
          最近更新 更多