使用shell命令按字符串对齐文本

时间:2014-02-09 04:21:10

标签: shell sed awk printf

说我在这样的文件中有一些文字:

lorem ipsum asdf gh 12345
hello, world! asdf gh this is a test
ee asdf gh ii

请注意,每行包含“asdf gh”。我希望能够使用一些shell命令来根据该分隔符字符串对齐该文本,所以我可以这样做:

$ cat my-file | some-command
lorem ipsum     asdf gh   12345
hello, world!   asdf gh   this is a test
ee              asdf gh   ii

在这个例子中,我在分隔符周围添加了额外的空格,但这两种方式并不重要。也就是说,输出也可以是:

$ cat my-file | some-command
lorem ipsum   asdf gh 12345
hello, world! asdf gh this is a test
ee            asdf gh ii

有一种简单的方法吗?我知道column可以列出事物,但它只能使用空格或字符(不是字符串或模式)作为分隔符。

3 个答案:

答案 0 :(得分:6)

awk是格式化输出的更好工具:

awk -F 'asdf gh' '{printf "%-15s%-10s%-10s\n", $1, FS, $2}'  file
lorem ipsum    asdf gh    12345    
hello, world!  asdf gh    this is a test
ee             asdf gh    ii    

您可以更改printf中的数字以进行更多自定义。

答案 1 :(得分:3)

在awk中使用printf函数

awk '{printf "%-20s%s\t%s\n",$1,FS,$2}' FS="asdf gh" file

lorem ipsum         asdf gh  12345
hello, world!       asdf gh  this is a test
ee                  asdf gh  ii

答案 2 :(得分:1)

除非您想使用awk并且有两个问题,否则您可以按照以下方式执行:

sed 's/asdf gh/%&/g' <my-file | column -t -s'%'

假设&#39;%&#39;是一个有效的分隔符,不会出现在您的文本中。

相关问题