How can you group consecutive lines in bash?

I have a file that looks like this:

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

I want to reformat it like this:

 abc def ghi jkl m 

I want the number of columns to be tuned. How could you do with bash? I can’t think of anything.

+6
source share
5 answers
 host:~ user$ cat file a b c d e f g h i j k l m host:~ user$ xargs -L3 echo < file abc def ghi jkl m host:~ user$ 

Replace β€œ3” with how many columns you want.

+9
source

A slightly improved version of xargs answer would be:

 xargs -n3 -r < file 

This method will better cope with the previous space and will not create a single empty line without input.

+4
source

Other:

 zsh-4.3.11[t]% paste -d\ - - - < infile abc def ghi jkl m 

Or (if you don't care about the last new line):

 zsh-4.3.11[t]% awk 'ORS = NR % m ? FS : RS' m=3 infile abc def ghi jkl m % 
+1
source
 column -x -c 30 /tmp/file abc def ghi jkl m 

Yes, the span is not quite what you wanted, but it handled input with a variable size β€œbetter” (better for some definitions).

+1
source

Since the < operator changes the order of things, I understood 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\ - - - 
+1
source

Source: https://habr.com/ru/post/888658/


All Articles