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.
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.
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.
From the bash manual: The backslash character '\' may be used to remove any special meaning for the next character read and for line continuation.
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\ - - -
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 %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With