【问题标题】:How can you group consecutive lines in bash?如何在 bash 中对连续的行进行分组?
【发布时间】:2011-05-20 15:48:27
【问题描述】:

我有一个如下所示的文件:

a
b
c
d
e
f
g
h
i
j
k
l
m

我想重新格式化它:

a b c
d e f
g h i
j k l
m

我希望列数是可配置的。你会怎么用bash?我什么都想不出来。

【问题讨论】:

    标签: bash command-line


    【解决方案1】:
    host:~ user$ cat file
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
    k
    l
    m
    host:~ user$ xargs -L3 echo < file
    a b c
    d e f
    g h i
    j k l
    m
    host:~ user$ 
    

    将“3”替换为您想要的列数。

    【讨论】:

    • 我首先想到的是sed 'N;N;s/\n/ /g' foo;为什么我没有想到使用xargs 进行文本操作?
    • 应该是-n3,不是吗? -L--max-lines-n--max-args
    • 回显是 xargs 的默认操作,所以 xargs -L3 &lt; file :)
    【解决方案2】:

    由于&lt; 运算符颠倒了事物的顺序,我想出了这个更直观的方法:

    cat file | xargs -n3
    

    但是,在对大文件进行测试后,paste 方法被证明要快得多:

    cat file | paste -d\ - - -
    

    【讨论】:

      【解决方案3】:

      xargs 答案的略微改进版本是:

      xargs -n3 -r < file
      

      这种方式可以更好地处理尾随空格,并避免为无输入创建单个空行

      【讨论】:

        【解决方案4】:

        另一个:

        zsh-4.3.11[t]% paste  -d\  - - - < infile
        a b c
        d e f
        g h i
        j k l
        m  
        

        或者(如果您不关心最后的换行符):

        zsh-4.3.11[t]% awk 'ORS = NR % m ? FS : RS' m=3 infile 
        a b c
        d e f
        g h i
        j k l
        m %     
        

        【讨论】:

          【解决方案5】:
          column -x -c 30 /tmp/file
          a       b       c
          d       e       f
          g       h       i
          j       k       l
          m
          

          是的,间距不是您想要的,但它会“更好地”处理可变大小的输入(对于一些更好的定义)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-07-22
            • 1970-01-01
            • 2017-04-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多