简体   繁体   English

如何在awk中使用if语句,以在Linux中对具有日期和其他值以分隔格式的文件使用

[英]How to use if statement in awk, for a file which has date and other values in delimited format in linux

I have a linux file with the below format, my requirement is the date (value) which are coming in the file in the columns (5,7) should be cut as per my substr command. 我有一个具有以下格式的linux文件,我的要求是文件(5,7)中即将出现的日期(值)应按照我的substr命令进行剪切。

Moreover, the 5th and 7th columns are those columns which may or may not contain the date(values.), so I need a if statement to correct the date values if present. 此外,第5列和第7列是那些可能包含也可能不包含date(values)的列,因此我需要一个if语句来更正日期值(如果存在)。

Kindly correct me with the proper script. 请使用正确的脚本纠正我。

SAMPLE FILE: 样本文件:

*# cat zx
7b540eda6b89136432213fbe09815c12,50281271950,,,20160524 08:14:26+0400,,20160524 08:14:26+0400,,7b540eda6b89136432213fbe09815c12,,,
7b540eda6b89136432213fbe09815c12,50281271950,,,,,20160524 08:14:26+0400,,7b540eda6b89136432213fbe09815c12,,,

My Script: 我的剧本:

awk -F "," '{print $1,$2,"",'BEGIN{if($5==""){print substr($5,1,4)"-"substr($5,5,2)"-"substr($5,7,11)}}',$6,'BEGIN{if($7==""){print substr($7,1,4)"-"substr($7,5,2)"-"substr($7,7,11)}}',$8,$9,$10,$11,$12}' OFS=, zx

ERROR THROWN: 错误抛出:

-bash: syntax error near unexpected token `('
awk -F, 'BEGIN{OFS=","} length($5)>0{$5=substr($5,1,4)"-"substr($5,5,2)"-"substr($5,7,11)} length($7)>0{$7=substr($7,1,4)"-"substr($7,5,2)"-"substr($7,7,11)} 1' file

Output: 输出:

7b540eda6b89136432213fbe09815c12,50281271950,,,2016-05-24 08:14:26,,2016-05-24 08:14:26,,7b540eda6b89136432213fbe09815c12,,,
7b540eda6b89136432213fbe09815c12,50281271950,,,,,2016-05-24 08:14:26,,7b540eda6b89136432213fbe09815c12,,,

This worked for me on my Solaris machine: 这在我的Solaris机器上对我有用:

/usr/xpg4/bin/awk -F',' '{printf "%s,%s,%s,", $1,$2,""} length($5)>0{printf "%s,", $5=substr($5,1,4)"-"substr($5,5,2)"-"substr($5,7,11)} {printf "%s,", $6} length($7)>0{printf "%s,", $7=substr($7,1,4)"-"substr($7,5,2)"-"substr($7,7,11)} {printf "%s,%s,%s,%s,%s\n", $8,$9,$10,$11,$12}' zx

Output: 输出:

7b540eda6b89136432213fbe09815c12,50281271950,,2016-05-24 08:14:26,,2016-05-24 08:14:26,,7b540eda6b89136432213fbe09815c12,,,
7b540eda6b89136432213fbe09815c12,50281271950,,,2016-05-24 08:14:26,,7b540eda6b89136432213fbe09815c12,,,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM