[20210924]awk奇怪的输出.txt
--//昨天在分析问题时使用awk,遇到一些奇怪的问题,做一个记录并加入自己的理解与分析:
.
1.环境:
SCOTT@test01p> @ ver1
PORT_STRING VERSION BANNER CON_ID
------------------------------ -------------- -------------------------------------------------------------------------------- ----------
IBMPC/WIN_NT64-9.1.0 12.2.0.1.0 Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production 0
2.测试:
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where 1=0;"
no rows selected
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;"
EMPNO DEPTNO SAL
---------- ---------- ----------
7369 20 800
7499 30 1600
7521 30 1250
7566 20 2975
7654 30 1250
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" | tr -d '\r' | awk '$2>=30 {print $0 }'
EMPNO DEPTNO SAL
7499 30 1600
7521 30 1250
7654 30 1250
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" | tr -d '\r' | awk '$2==30 {print $0 }'
7499 30 1600
7521 30 1250
7654 30 1250
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" | tr -d '\r' | awk '$2==20 {print $0 }'
7369 20 800
7566 20 2975
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" | tr -d '\r' | awk '$2==20 && $3>=1000 {print $0 }'
7566 20 2975
--//注:windows下使用cygwin输出文本带有\r,必须过滤掉,不然输出混乱.
--//你可以发现一个现象,使用awk过滤,有时输出header有一些没有,但是不会输出分隔线---.为什么呢?
--// 字符 - 2 3 D对应的ascii码如下:
--// - = 2d
--// 2 = 32
--// 3 = 33
--// D = 44
--//你可以发现条件 $2>=30 出现header的主要原因是awk把它当作字符串处理的,或者讲当$2是字符串时,条件变成了 $2 >= '30';这样输
--//出在条件$2>=30的情况下输出header就很正常了.等价于如下:
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" | tr -d '\r' | awk '$2>='30' {print $0 }'
EMPNO DEPTNO SAL
7499 30 1600
7521 30 1250
7654 30 1250
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" | tr -d '\r' | awk '$2>="30" {print $0 }'
EMPNO DEPTNO SAL
7499 30 1600
7521 30 1250
7654 30 1250
--//如何取消呢?很简单加入一点点运算,修改如下:
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" 2>&1 | tr -d '\r' | awk '$2*1>=30 {print $0 }'
7499 30 1600
7521 30 1250
7654 30 1250
$ sqlplus -s -l scott/btbtms@test01p <<< "select empno,deptno,sal from emp where rownum<=5;" 2>&1 | tr -d '\r' | awk '$2+0>=30 {print $0 }'
7499 30 1600
7521 30 1250
7654 30 1250
--//将条件修改为$2*1>=30 或者 $2+0 >=30 就可以过滤header.
--//不知道各位还有什么好方法,大家给一个建议.