开发者

How can you group consecutive lines in bash?

开发者 https://www.devze.com 2023-03-07 19:49 出处:网络
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开发者_如何学C l

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开发者_如何学C l
m

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


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.


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


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 %     


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\ - - -


column -x -c 30 /tmp/file
a       b       c
d       e       f
g       h       i
j       k       l
m

Yes, the spacing isn't exactly what you wanted, but it would handle variable sized inputs "better" (for some definitons of better).

0

精彩评论

暂无评论...
验证码 换一张
取 消