regex - 使用 Sed 将文本文件中的列右对齐

标签 regex bash unix awk sed

我有一个包含大量信息的文件,我想以特定格式获取这些信息,即在不同列之间添加特定数量的空格。我可以在每一行中添加相同数量的空格,但有些列需要右对齐,这意味着我可能需要在某些行中添加更多空格。我不知道该怎么做,awk 似乎不起作用,因为我修改了两行以上。

这是一个例子:

我已经设法得到一个看起来像这样的文件

apple   1   33.413 C     cat    10
banana   2   21.564 B     horse    356
cherry   3   43.223 D     cow    32
pear   4   26.432 A     goat    22
raspberry   5   72.639 C     eagle    4
watermelon   6   54.436 A     fox    976
pumpkin   7   42.654 B     mouse    1
peanut   8   36.451 B     dog    56
orange   9   57.333 C     elephant    32
coconut   10   10.445 A     frog    3
blueberry   11   46.435 B     camel    446

但是我想得到这种格式的文件

apple         1   33.413 C          cat    10
banana        2   21.564 B        horse    356
cherry        3   43.223 D          cow    32
pear          4   26.432 A         goat    22
raspberry     5   72.639 C        eagle    4
watermelon    6   54.436 A          fox    976
pumpkin       7   42.654 B        mouse    1
peanut        8   36.451 B          dog    56
orange        9   57.333 C     elephant    32
coconut      10   10.445 A         frog    3
blueberry    11   46.435 B        camel    446 

我可以使用什么 bash 命令来右对齐第二列和第五列?

最佳答案

你可以使用 printf 和你想要的宽度:

awk '{printf "%-15s%3d%10s%2s%15s    %-5d\n", $1, $2, $3, $4, $5, $6}' file
apple            1    33.413 C            cat    10
banana           2    21.564 B          horse    356
cherry           3    43.223 D            cow    32
pear             4    26.432 A           goat    22
raspberry        5    72.639 C          eagle    4
watermelon       6    54.436 A            fox    976
pumpkin          7    42.654 B          mouse    1
peanut           8    36.451 B            dog    56
orange           9    57.333 C       elephant    32
coconut         10    10.445 A           frog    3
blueberry       11    46.435 B          camel    446

随意调整宽度以调整输出。

关于regex - 使用 Sed 将文本文件中的列右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896158/

相关文章:

regex - 修复正则表达式中的灾难性回溯

linux - 在 bash 中获取新添加的文件

algorithm - 文件的交集

linux - 如何在 bash 中提供输入 [通过网络执行]

c++ - Unix 套接字 : select() with more than one set associated does more than it should do

unix - 从文件/grep 中删除重复的行

c# - (C#) Regex.Matches 找出最小长度匹配字符串

Java 8 - Lambda 表达式将 List<String> 转换为 List<DTO>

PHP - 获取这些值的更好方法?

bash - 向应用程序发送命令并通过 bash 中的文件描述符读取其输出