awk没有检查statment是否与输出中的所有打印行相关联

时间:2016-04-01 08:22:56

标签: shell awk

我正在尝试编写以下代码,但awk没有正确检查if语句

#!/bin/bash

sqlplus -S username/pwd << EOF

SET ECHO off;
Set FEEDBACK off;
SET TRIMSPOOL on;
SET TAB off;
SET TERMOUT OFF;
set HEADSEP off;
SET HEADING on;
SET LINESIZE 1000;
SET WRAP off;
set serveroutput off;

SPOOL /tmp/sql_output.xls
select  * from (
select  PROCESS_SRC_STATUS_IND,PROCESS_RUN_TIME_ID,PROCESS_ID from      raptore.tb_process_prod c 
where PROCESS_ID in (116)
order by PROCESS_CREATE_DTM desc
)
where rownum=1

spool off
exit;
EOF

awk '{

if ( $1 == "C")
then
    print "Job J4051 has successfully run for date " $2 

elif ($1 == "P")
then
    print "Job J4051 is pending for date " $2 

elif ($1 == "F")
then
    print "Job J4051 is failed for date " $2

}' /tempt/sql_output.xls

sql查询输出:

C 20160330 116

脚本输出:

Job J4051已成功运行20160330日期 Job J4051正在等待20160330日期 作业J4051在20160330日期失败

理想情况下输出shud只是上述行中的一行,但脚本正在打印所有打印行作为输出。请帮助

2 个答案:

答案 0 :(得分:4)

then awk's条款中没有if

语法应如下所示

awk '
    {

    if(conditional-expression1)
        action1;
    else if(conditional-expression2)
        action2;
    else if(conditional-expression3)
        action3;
        .
        .
    else
        action n;
    }
   '
  • 如果condition-expression1为true,则action1将为 进行。
  • 如果条件表达式1为假,则为conditional-expression2 将被检查,如果它是真的,将执行action2并继续 像这样。如果没有,那么最后的其他部分将被执行 条件表达式为真。

如下修改

awk '{
            if ( $1 == "C")
                print "Job J4051 has successfully run for date " $2 
       else if ( $1 == "P" )
                print "Job J4051 is pending for date " $2 
       else if ( $1 == "F" )
                print "Job J4051 is failed for date " $2
     }
    '  infile

答案 1 :(得分:3)

更加惯用的awk版本

 $ awk '$1=="C"{text="Job J4051 has successfully run for date"} 
        $1=="P"{text=...} 
        ... 
        {print text, $2}' file