Join N number of lines recursively
awk
is your friend:
$ awk 'ORS=NR%3?FS:RS' fileThis is line 1 This is line 2 This is line 3 This is line 4 This is line 5 This is line 6 This is line 7 This is line 8 This is line 9
Which is the same as:
$ awk 'ORS=NR%3 ? " " : "\n"' fileThis is line 1 This is line 2 This is line 3 This is line 4 This is line 5 This is line 6 This is line 7 This is line 8 This is line 9
Explanation
If number of record is not multiple of 3, then set the output record separator as space; otherwise, as new line.
ORS
defines the output record separator.NR
defines the number of records (lines in this case).FS
defines the fields separators. Default is" "
(space).RS
defines the records separators. Default is"\n"
(new line).
More info and related examples in Idiomatic awk.
sed version
sed -e '$ b printN$ b printN:prints/\n/ /g' YourFile
if there is only multiple of 3 lines, the $ b print
and :print
are not necessary
in one line version
for non GNU sed (like my AIX)
sed -e '$bprint' -e 'N;$bprint' -e 'N;:print' -e 's/\n/ /g' YourFile
for GNU sed (no tested, missing linux here)
sed -e '$bprint;N;$bprint;N;:print;s/\n/ /g' YourFile