简体   繁体   中英

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

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:

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

Using 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

With GNU sed:

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

and short version:

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

Here's one sed solution:

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\}\)/\1\n/g'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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