5

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
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
user2275669
  • 53
  • 1
  • 3

5 Answers5

11
$ 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
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
  • 2
    Well, xargs seems so obvious _now_ :-) – William Apr 12 '13 at 20:21
  • Really clever use of xargs -n! Would've never thought of that, was going the awk route. – Samuel Tan Jul 27 '16 at 03:54
  • This gave me some issues when working with transcripts involving ad-hoc use of the apostrophe: xargs tries to match them in pairs; treats the contents of a pair as a single argument; doesn't insert newlines in such contents; and also removes the apostrophes. I overcame this by explicitly specifying a space as delimiter via `-d' '`. So `xargs -d' ' -n3 < file` allows me to handle: "We were born in t' earth beyond t' land". (Using `-0` didn't work btw.) – user2023370 Feb 01 '23 at 17:55
0

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
Birei
  • 35,723
  • 2
  • 77
  • 82
0

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
perreal
  • 94,503
  • 21
  • 155
  • 181
0

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'
William
  • 4,787
  • 2
  • 15
  • 14
0

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

 cat myfile.txt | perl -lane 'while(($a,$b,$c) = splice(@F,0,3)){print "$a $b $c"}'
Magnus
  • 10,736
  • 5
  • 44
  • 57
  • I'd say AUUoCA - Almost UUoCA... its use is that I find this conceptually easier to comprehend, because I read from left to right I like thinking about my data flow in the same direction. Also this maintains 1 arg per command so there's never any confusion about correct ordering of args. – Magnus Apr 13 '13 at 02:47