在Linux中,有没有办法在分隔符上对齐文本?

时间:2013-10-02 03:20:30

标签: linux shell sed text-alignment

我有一个基本上运行tmux ls的脚本:

session1: 3 windows (created Fri Sep 20 13:16:13 2013) [157x56]
stuff: 3 windows (created Fri Sep 20 13:25:21 2013) [157x56]
asdf: 2 windows (created Sun Sep 29 23:06:33 2013) [77x17] (attached)
website: 1 windows (created Tue Sep 24 17:22:14 2013) [157x26]

为了便于阅读,我希望此脚本的输出在冒号处对齐。我知道要使用column -t,但它并不能完全符合我的要求(注意双倍间距,并且冒号实际上没有对齐):

session1:  3  windows  (created  Fri  Sep  20  13:16:13  2013)  [157x56]
stuff:     3  windows  (created  Fri  Sep  20  13:25:21  2013)  [157x56]
asdf:      2  windows  (created  Sun  Sep  29  23:06:33  2013)  [77x17]   (attached)
website:   1  windows  (created  Tue  Sep  24  17:22:14  2013)  [157x26]

这是我真正想要的输出:

session1 : 3 windows (created Fri Sep 20 13:16:13 2013) [157x56]
stuff    : 3 windows (created Fri Sep 20 13:25:21 2013) [157x56]
asdf     : 2 windows (created Sun Sep 29 23:06:33 2013) [77x17] (attached)
website  : 1 windows (created Tue Sep 24 17:22:14 2013) [157x26]

在Linux shell中实现这一目标的最简单/最好的方法是什么?


修改:如果您想测试答案,可以使用curl -s nylen.tv/tmux.txt代替tmux ls

2 个答案:

答案 0 :(得分:3)

使用GNU sed,您可以指定匹配的发生次数,以便s/ +/ /g单个空格,整个文件s/ +/ /2g单个空格整个文件,但在每行第二个匹配后:< / p>

$ column -t file | sed -re 's/: ( +)/\1: /' -e 's/ +/ /2g'
session1 : 3 windows (created Fri Sep 20 13:16:13 2013) [157x56]
stuff    : 3 windows (created Fri Sep 20 13:25:21 2013) [157x56]
asdf     : 2 windows (created Sun Sep 29 23:06:33 2013) [77x17] (attached)
website  : 1 windows (created Tue Sep 24 17:22:14 2013) [157x26]

要整理第一列间距,我们使用s/: ( +)/\1: /来匹配:中的所有空格,并在第一个捕获组中存储n-1个空格。然后,我们将:和所有空格替换为n-1个空格,后跟一个:,后跟一个空格(再次创建n个空格)

答案 1 :(得分:1)

这个怎么样?

cat tmux.txt | sed 's/:/ : /' | column -t -o' ' | sed 's/ \+/ /2g' 
session1 : 3 windows (created Fri Sep 20 13:16:13 2013) [157x56]
stuff    : 3 windows (created Fri Sep 20 13:25:21 2013) [157x56]
asdf     : 2 windows (created Sun Sep 29 23:06:33 2013) [77x17] (attached)
website  : 1 windows (created Tue Sep 24 17:22:14 2013) [157x26]