如果字段为空或空白,如何打印空格

时间:2015-07-09 15:44:56

标签: awk

我的文件为x.log

07/08/15   05:00:00   07/08/15   05:00:20   DB_XXXLNX9           XXXLNX9    Completed
07/09/15   05:00:00   07/09/15   05:00:34   DB_XXXLNX9           XXXLNX9    Failed
07/10/15   05:00:00   DB_XXXLNX9 BETLNX9    Future

如果任何字段为空,我需要打印相同格式的列。即DB_XXXLNX9应该在上面的DB_XXXLNX9之下。出于某种原因,我不能在这个问题上打印出来,我道歉。

07/08/15   05:00:00   07/08/15   05:00:20   DB_XXXLNX9           XXXLNX9    Completed
07/09/15   05:00:00   07/09/15   05:00:34   DB_XXXLNX9           XXXLNX9    Failed
07/10/15   05:00:00                         DB_XXXLNX9           XXXLNX9    Future

我尝试了这个awk语句

awk '{printf "%-10s %-10s %-10s %-10s %-20s %-10s %-10s\n", $1, $2, $3, $4, $5, $6, $7}' x.log 

2 个答案:

答案 0 :(得分:2)

这可能是您想要的,如果没有更多信息和额外的样本输入/输出,很难说:

$ awk -v OFS=, 'NF<7{$3=OFS OFS $3} {$1=$1}1' file | column -s, -t
07/08/15  05:00:00  07/08/15  05:00:20  DB_XXXLNX9  XXXLNX9  Completed
07/09/15  05:00:00  07/09/15  05:00:34  DB_XXXLNX9  XXXLNX9  Failed
07/10/15  05:00:00                      DB_XXXLNX9  BETLNX9  Future

答案 1 :(得分:0)

不是一个令人满意的解决方案,但工作正常:

 awk '{
    if (NF==5) {
      printf "%-10s %-10s %-10s %-10s %-10s %-10s%-10s %-10s\n", $1, $2, "", "", $3, "", $4, $5; }
    else
      print;
}' x.log

对于不完整的行,确切的空间填充很奇怪但需要适合OP:注意没有任何空格的addtionnal %-10s。这是由于原始格式。

请注意,您无法使用OFMT来简化此行,因为它的目的是仅用于浮点数。