使用awk添加常量值

时间:2018-09-17 09:46:04

标签: shell unix awk scripting

如果值小于010000,我需要在第4列添加常数。常数值为awk '{ if($4 -lt 240000) $4= $4+010000; }' Test.txt 。我已经写了命令,但没有给出任何输出。以下是示例数据和脚本。请为此提供帮助。谢谢。

命令:

1039,1018,20180915,000000,0,0,A
1039,1018,20180915,010000,0,0,A
1039,1018,20180915,020000,0,0,A
1039,1018,20180915,030000,0,0,A
1039,1018,20180915,240000,0,0,A
1039,1018,20180915,050000,0,0,A
1039,1018,20180915,060000,0,0,A
1039,1018,20180915,070000,1,0,A
1039,1018,20180915,080000,0,1,A
1039,1018,20180915,090000,2,0,A
1039,1018,20180915,241000,0,0,A
1039,1018,20180915,240500,0,0,A 

样本数据:

<select>

1 个答案:

答案 0 :(得分:2)

$ awk  '
BEGIN { FS=OFS="," }                 # input and output field separators
{
    if($4<240000)                    # if comparison
        $4=sprintf("%06d",$4+10000)  # I assume 10000 not 010000, also zeropadded to 6 chars
        # $4+=10000                  # if zeropadding is not required
    print                            # output
 }' file

输出:

1039,1018,20180915,010000,0,0,A
1039,1018,20180915,020000,0,0,A
1039,1018,20180915,030000,0,0,A
1039,1018,20180915,040000,0,0,A
1039,1018,20180915,240000,0,0,A
1039,1018,20180915,060000,0,0,A
1039,1018,20180915,070000,0,0,A
1039,1018,20180915,080000,1,0,A
1039,1018,20180915,090000,0,1,A
1039,1018,20180915,100000,2,0,A
1039,1018,20180915,241000,0,0,A
1039,1018,20180915,240500,0,0,A

$4+10000不是010000,因为awk 'BEGIN{ print 010000+0}'输出4096,因为它是该值的八进制表示形式。