我有一个基本上可以运行 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
.
最佳答案
使用 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 个空格,后跟一个 :
后跟一个空格 (再次使总空间为 n) .
关于linux - 在 Linux 中,有没有办法在分隔符上对齐文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19129485/