【问题标题】:Join N number of lines recursively递归加入 N 行
【发布时间】:2014-07-09 22:40:41
【问题描述】:

如何在 shell 脚本中实现以下结果?

This is line 1  
This is line 2  
This is line 3  
This is line 4  
This is line 5  
This is line 6  
This is line 7  
This is line 8  
This is line 9  
...  
...  

期望的输出:

This is line 1 This is line 2 This is line 3  
This is line 4 This is line 5 This is line 6  
This is line 7 This is line 8 This is line 9  
... ... ....  
... ... ...  

【问题讨论】:

    标签: linux shell awk sed tr


    【解决方案1】:

    这可能对你有用(GNU sed):

    sed '$!N;$!N;y/\n/ /' file
    

    【讨论】:

    • 比我的好多了+1
    【解决方案2】:

    sed 版本

    sed -e '$ b print
    N
    $ b print
    N
    :print
    s/\n/ /g' YourFile
    

    如果只有 3 行的倍数,则不需要 $ b print:print

    单行版本

    • 对于非 GNU sed(比如我的 AIX)

      sed -e '$bprint' -e 'N;$bprint' -e 'N;:print' -e 's/\n/ /g' YourFile

    • 对于 GNU sed(未测试,这里缺少 linux)

      sed -e '$bprint;N;$bprint;N;:print;s/\n/ /g' YourFile

    【讨论】:

      【解决方案3】:

      试试这个,

      paste -d " " - - - < file
      

      这个以空格为分隔符的粘贴命令将连续的 3 行合并为一行。

      【讨论】:

      • 你也可以使用paste -d " " - - - &lt; file
      【解决方案4】:

      awk是你的朋友:

      $ awk 'ORS=NR%3?FS:RS' file
      This is line 1   This is line 2   This is line 3  
      This is line 4   This is line 5   This is line 6  
      This is line 7   This is line 8   This is line 9 
      

      等同于:

      $ awk 'ORS=NR%3 ? " " : "\n"' file
      This is line 1   This is line 2   This is line 3  
      This is line 4   This is line 5   This is line 6  
      This is line 7   This is line 8   This is line 9  
      

      说明

      如果记录数不是3的倍数,则设置输出记录分隔符为空格;否则,作为新行。

      • ORS 定义输出记录分隔符。
      • NR 定义记录数(本例中为行数)。
      • FS 定义字段分隔符。默认为" "(空格)。
      • RS 定义记录分隔符。默认为"\n"(新行)。

      Idiomatic awk 中的更多信息和相关示例。

      【讨论】:

      • 我比paste 更喜欢这个解决方案,因为它要求n number of lines 而这个awk 可以很容易地调整为任何数字。
      • 酷。只是不要将 FS 或 RS 设置为空字符串。
      • 谢谢,@glennjackman,我不明白你是否说这与我所写的或一般意义上的 RS/FS 有关。
      • 就是这个。一个例子:seq 10 | awk -F "" 'ORS=NR%5?FS:RS' 可能不会输出你所期望的。空字符串为假,所以隐含的print没有做完。
      • 谢谢,得到了想要的输出。还请解释对我有很大帮助。
      猜你喜欢
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多