如何使用awk或sed在bash中调整列字段的长度? [英] How can I adjust the length of a column field in bash using awk or sed?
问题描述
我有一个input.csv文件,其中列2和3有变量lengtt。
I've an input.csv file in which columns 2 and 3 have variable lengtt.
100,Short Column, 199
200,Meeedium Column,1254
300,Loooooooooooong Column,35
我试图使用下面的命令来实现一个干净的列表,但我需要填充一定数量的空格,以获得一个固定的长度列(让我们说,总长度为30就足够了) 。
I'm trying to use the following command to achieve a clean tabulation, but I need to fill the 2nd column with a certain number of blank spaces in order to get a fixed lenght column (let's say that a total lenght of 30 is enough).
awk -F, '{print $1 "\t" $2 "\t" $3;}' input.csv
我当前的输出如下所示:
My current output looks like this:
100 Short Column 199
200 Meeedium Column 1254
300 Loooooooooooong Column 35
我想通过正确填充第二和第三列来实现以下输出:
And I would like to achieve the following output, by filling 2nd and 3rd column properly:
100 Short Column 199
200 Meeedium Column 1254
300 Loooooooooooong Column 35
任何好的想法有关于awk或sed命令应该使用?
感谢大家。
Any good idea out there about awk or sed command should be used? Thanks everybody.
推荐答案
不要选择任意数字作为每个字段的宽度,方法,其中第一遍计算每个字段的最大长度,第二遍打印字段的宽度加上字段之间的几个空格:
Rather than picking some arbitrary number as the width of each field, do a 2-pass approach where the first pass calculates the max length of each field and the 2nd prints the fields in a width that size plus a couple of spaces between fields:
$ cat tst.awk
BEGIN { FS=" *, *"; OFS=" " }
NR==FNR {
for (i=1;i<=NF;i++) {
w[i] = (length($i) > w[i] ? length($i) : w[i])
if ($i ~ /[^0-9]/) {
a[i] = "-"
}
}
next
}
{
for (i=1;i<=NF;i++) {
printf "%"a[i]w[i]"s%s", $i, (i<NF ? OFS : ORS)
}
}
$ awk -f tst.awk file file
100 Short Column 199
200 Meeedium Column 1254
300 Loooooooooooong Column 35
上面还使用左对齐用于非数字字段,右对齐用于全数字字段。无论输入字段有多长,无论有多少字段,它都会工作:
The above also uses left-alignment for non-digit fields, right alignment for all-digits fields. It'll work no matter how long the input fields are and no matter how many fields you have:
$ cat file1
100000,Short Column, 199,a
100,Now is the Winter of our discontent with fixed width fields,20000,b
100,Short Column, 199,c
200,Meeedium Column,1254,d
300,Loooooooooooong Column,35,e
$ awk -f tst.awk file1 file1
100000 Short Column 199 a
100 Now is the Winter of our discontent with fixed width fields 20000 b
100 Short Column 199 c
200 Meeedium Column 1254 d
300 Loooooooooooong Column 35 e
这篇关于如何使用awk或sed在bash中调整列字段的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!