繁体   English   中英

如何使用AWK或Sed在x个单词之后插入换行符\\ n

[英]how to insert a newline \n after x numbers of words, with AWK or Sed

我在一行中有这个:

We were born in the earth beyond the land

我希望它在3个单词行中,如下所示:

We were born
in the earth 
beyond the land
$ 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

使用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

使用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

这是一个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'

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM