【问题标题】:how to insert a newline \n after x numbers of words, with AWK or Sed如何使用 AWK 或 Sed 在 x 个单词后插入换行符 \n
【发布时间】:2013-04-12 19:53:15
【问题描述】:

我在一行中有这个:

We were born in the earth beyond the land

我希望它在 3 个单词的行中,是这样的:

We were born
in the earth 
beyond the land

【问题讨论】:

  • 您能展示一下您为此尝试过的代码吗?

标签: linux bash shell unix awk


【解决方案1】:
$ xargs -n3 < file
We were born
in the earth
beyond the land

$ egrep -o '\S+\s+\S+\s+\S+' file 
We were born
in the earth
beyond the land

【讨论】:

  • 好吧,xargs 看起来很明显现在 :-)
  • xargs -n 的使用真的很巧妙!从来没有想过,会走 awk 路线。
【解决方案2】:

使用awk:

awk '{ 
    for ( i = 1; i <= NF; i++ ) { 
        printf "%s%c", $i, (i % 3 == 0) ? ORS : OFS 
    } 
}' infile

它产生:

We were born
in the earth
beyond the land

【讨论】:

    【解决方案3】:

    使用 GNU sed:

    sed 's/\(\w\w*\W*\w\w*\W*\w\w*\W*\)/\1\n/g' input
    

    和短版:

    sed 's/\(\(\w\w*\W*\)\{3\}\)/\1\n/g' input
    

    【讨论】:

      【解决方案4】:

      这是一个 sed 解决方案:

      sed -e 's/\s/\n/3;s/\s/\n/6;s/\s/\n/9'
      

      它将第三、第六和第九个空格替换为换行符。

      这个可以处理更长的行,即使它们不是三个单词的倍数:

      sed -e 's/\(\(\S\{1,\}\s*\)\{3\}\)/\1\n/g'
      

      【讨论】:

        【解决方案5】:

        任何有 awk 和 sed 的系统几乎肯定也会有 Perl:

         cat myfile.txt | perl -lane 'while(($a,$b,$c) = splice(@F,0,3)){print "$a $b $c"}'
        

        【讨论】:

        • 我会说 AUUoCA - 几乎是 UUoCA ......它的用途是我发现这在概念上更容易理解,因为我从左到右阅读我喜欢在同一个方向思考我的数据流。这也为每个命令维护 1 个 arg,因此对于 args 的正确顺序永远不会有任何混淆。
        猜你喜欢
        • 2023-03-26
        • 2023-02-06
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        • 2013-06-26
        • 2012-03-26
        • 1970-01-01
        相关资源
        最近更新 更多