如何在 bash 中对连续行进行分组?
我有一个如下所示的文件:
a
b
c
d
e
f
g
h
i
j
k
l
m
我想将其重新格式化为:
a b c
d e f
g h i
j k l
m
我希望列数是可配置的。你会怎样用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将“3”替换为您想要的列数。
Replace '3' with how many columns you want.
xargs 答案的稍微改进版本是:
这种方式可以更好地处理尾随空白,并避免为无输入创建单个空行
A slightly improved version of the xargs answer would be:
This way would handle trailing whitespace better and avoid creating a single empty line for no input
另一种:
或者(如果你不关心最后的换行符):
Another one:
Or (if you don't care about the final newline):
由于
<
运算符颠倒了事物的顺序,我想出了这种更直观的方法:但是,在对大文件进行测试之后,结果证明
paste
方法要快得多:Since the
<
operator reverses the order of things, I figured out this more intuitive approach:However, after tests with large files, the
paste
approach turned out to be much faster:是的,间距并不完全是您想要的,但它可以“更好”地处理可变大小的输入(对于某些更好的定义)。
Yes, the spacing isn't exactly what you wanted, but it would handle variable sized inputs "better" (for some definitons of better).