我有一个包含大量信息的文件,我想以特定格式获取这些信息,即在不同列之间添加特定数量的空格。我可以在每一行中添加相同数量的空格,但有些列需要右对齐,这意味着我可能需要在某些行中添加更多空格。我不知道该怎么做,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/