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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15979802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:10:55  来源:igfitidea点击:

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

linuxbashshellunixawk

提问by user2275669

I have this in one line:

我在一行中有这个:

We were born in the earth beyond the land

I want it in 3 words lines, to be like this:

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

We were born
in the earth 
beyond the land

回答by Chris Seymour

$ 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

回答by Birei

Using awk:

使用awk

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

It yields:

它产生:

We were born
in the earth
beyond the land

回答by perreal

With GNU sed:

使用 GNU sed:

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

and short version:

和简短版本:

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

回答by William

Here's one sed solution:

这是一个 sed 解决方案:

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

It replaces the third, sixth and ninth spaces with newlines.

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

This one will handle longer lines, even if they aren't multiples of three words:

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

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

回答by Magnus

Any system that has awk and sed will almost certainly also have Perl:

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

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