4

我在一行中有这个:

We were born in the earth beyond the land

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

We were born
in the earth 
beyond the land
4

5 回答 5

10
$ 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
于 2013-04-12T19:58:24.383 回答
0

使用 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
于 2013-04-12T20:08:14.693 回答
0

使用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
于 2013-04-12T20:00:55.833 回答
0

这是一个 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'
于 2013-04-12T20:12:44.400 回答
0

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

 cat myfile.txt | perl -lane 'while(($a,$b,$c) = splice(@F,0,3)){print "$a $b $c"}'
于 2013-04-12T20:13:02.953 回答