3

我有一个基本上可以运行的脚本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.

4

2 回答 2

4

使用GNU sed您可以指定匹配的出现,以便s/ +/ /g将整个文件的s/ +/ /2g单个空格单个空格整个文件,但在每行的第二个匹配之后:

$ 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 个空格、a:和一个空格替换所有空格(再次生成 n 个总空间)

于 2013-10-02T08:03:57.030 回答
2

这个怎么样?

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]
于 2013-10-02T03:33:14.680 回答