是否可以为unix中的列分配特定长度?

时间:2016-12-03 11:07:23

标签: python shell unix awk sed

我想以适当的格式打印所有列,是否有任何命令用于分配具有特定长度的列。我使用" \ t"这给了我低于输出(class(anydate(my_dates)) #[1] "Date" )但我想要File.txt

FILE.TXT

Required_output.txt

Required_output.txt

Dec 2    amlfx_HDW_20161202.txt  01:05   12.70
Dec 2    amltxn_HDW_20161202.txt         01:06   85.72
Dec 2    amlsecmstr_HDW_20161202.txt     01:05   0.000

我使用了命令,我希望在awk语句中以11美元和10美元的空间管理。

Dec 2    amlfx_HDW_20161202.txt          01:05   12.70
Dec 2    amltxn_HDW_20161202.txt         01:06   85.72
Dec 2    amlsecmstr_HDW_20161202.txt     01:05   0.000

2 个答案:

答案 0 :(得分:1)

您可以像这样使用string formatting

In [33]: c1 = "hello"

In [34]: c2 = "world"

In [35]: print "{:10s}{:10s}".format(c1, c2)
hello     world

{:10s}基本上将您的文字与左侧对齐,大小为10个字符。

答案 1 :(得分:0)

测试数据:

$ cat test.txt
Dec 2 amlfx_HDW_20161202.txt  01:05 12.70
Dec 2 amltxn_HDW_20161202.txt 01:06 85.72
Dec 2 amlsecmstr_HDW_20161202.txt 01:05 0.000

awk脚本:

BEGINFILE{
   # FILENAME: built-in var
   # get max width of each column
   while(getline < FILENAME)
   {
        for(j=1;j<=NF;j++)
        if(width_ary[j-1]<length($j))
            width_ary[j-1] = length($j)
   }
}

{
    for(i=1; i<=NF; i++)
    {
        if (i < NF)
        {
            # to get format string like this: '%-10s    '
            fmt = sprintf("%%-%ds    ", width_ary[i-1])
            printf(fmt, $i)
        }
        else{
            fmt = sprintf("%%-%ds    \n", width_ary[i-1])
            printf(fmt, $i)
        }
    }
}

输出:

$ awk -f t.awk test.txt
Dec    2     amlfx_HDW_20161202.txt         01:05    12.70
Dec    2     amltxn_HDW_20161202.txt        01:06    85.72
Dec    2     amlsecmstr_HDW_20161202.txt    01:05    0.000
Dec    12    amlsecmstr_HDW_20161212.txt    02:05    10.10

AWK版本:

awk -V
GNU Awk 4.1.3, API: 1.1
Copyright (C) 1989, 1991-2015 Free Software Foundation.