Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you group consecutive lines in bash?

I have a file that looks like the following:

a
b
c
d
e
f
g
h
i
j
k
l
m

I want to reformat it like:

a b c
d e f
g h i
j k l
m

I want the number of columns to be configurable. How would you that with bash? I can't think of anything.

like image 446
static_rtti Avatar asked May 20 '11 15:05

static_rtti


People also ask

How to combine lines in Linux?

Join Without a Delimiter. The tr command can solve this problem in a pretty straightforward way. If we remove all linebreaks from the file content, all lines will be joined together: $ tr -d '\n' < input.

What are [] in bash?

The closing bracket tells test where the expression ends. The double brackets ([[) are a bash built in and can replace the external call to test.

How do I continue a new line in bash?

From the bash manual: The backslash character '\' may be used to remove any special meaning for the next character read and for line continuation.


4 Answers

Since the < operator reverses the order of things, I figured out this more intuitive approach:

cat file | xargs -n3

However, after tests with large files, the paste approach turned out to be much faster:

cat file | paste -d\ - - -
like image 74
antoineMoPa Avatar answered Oct 19 '22 13:10

antoineMoPa


host:~ user$ cat file
a
b
c
d
e
f
g
h
i
j
k
l
m
host:~ user$ xargs -L3 echo < file
a b c
d e f
g h i
j k l
m
host:~ user$ 

Replace '3' with how many columns you want.

like image 21
yan Avatar answered Oct 19 '22 12:10

yan


A slightly improved version of the xargs answer would be:

xargs -n3 -r < file

This way would handle trailing whitespace better and avoid creating a single empty line for no input

like image 6
sehe Avatar answered Oct 19 '22 11:10

sehe


Another one:

zsh-4.3.11[t]% paste  -d\  - - - < infile
a b c
d e f
g h i
j k l
m  

Or (if you don't care about the final newline):

zsh-4.3.11[t]% awk 'ORS = NR % m ? FS : RS' m=3 infile 
a b c
d e f
g h i
j k l
m %     
like image 4
Dimitre Radoulov Avatar answered Oct 19 '22 11:10

Dimitre Radoulov