$ cat test.out
SCHEMA1pr TAB
SCHEMA2asdff MEDIUMTABLE
SCHEMA3adf LONG_TABLE_NAME_THAT_HAS_A_LONG_NAME
S1 T1
S1ABC T1AB
$
在AWK中,$0表示整行,$1表示第一列,$2表示第二列
####这个列子使用了空格作为列分隔符
$ cat test.out | awk '{print $1}'
SCHEMA1pr
SCHEMA2asdff
SCHEMA3adf
S1
S1ABC
$
####每个列左(-)对齐,每个列20个字符,字符不足的列用空格代替
$ cat test.out | awk '{printf "%-20s %-20s\n", $1,$2}'
SCHEMA1pr TAB
SCHEMA2asdff MEDIUMTABLE
SCHEMA3adf LONG_TABLE_NAME_THAT_HAS_A_LONG_NAME
S1 T1
S1ABC T1AB
$
$ cat test.out | awk '{printf "%20s %20s\n", $1,$2}'
SCHEMA1pr TAB
SCHEMA2asdff MEDIUMTABLE
SCHEMA3adf LONG_TABLE_NAME_THAT_HAS_A_LONG_NAME
S1 T1
S1ABC T1AB
$
####可以灵活使用awk的作用来生成一些sql
db2 -x "select char(tabschema, 20), char(tabname, 70) from syscat.tables where type = 'T' and tabschema like '%EP%' with ur" > tables.list
cat tables.list | awk '{print "grant select, insert, update, delete on table "$1"."$2" to role developer;"}' > grant.sql
db2 –tvf grant.sql | tee grant.sql.log
####可以写一行来做这个事情
####注:这个地方是一行行的执行,不是执行一个SQL文件,就不用加分号;了
db2 -x "select char(tabschema, 20), char(tabname, 70) from syscat.tables where type = 'T' and tabschema like '%EP%' with ur" | awk '{print "grant select on table "$1"."$2" to user epriw"}' | db2 -v | tee –a grant.log
####假设你有一个DDL文件,想提取里面的table name,并且grant privilege
####这里用-F '.'来指定分隔符为.
cat $ddl | grep -i "create table" | awk '{print $3}' | awk -F '.' '{print "grant select, insert, update, delete on table "$1" "$2" to user epradm;"}' > grant.sql
db2 –tvf grant.sql | tee grant.sql.log
####假设你有一个文件,其中包含了一些表
$ cat list.txt
EPRICER.CTMTCOM
EPRICER.CTMTTRN
####你想查看这些表的indexes
####special assignment operator '-v'
cat list.txt | awk -F '.' -v x="'" '{print "select char(tabschema, 20), char(tabname, 60), char(colnames, 200) from syscat.indexes where tabschema="x$1x" and tabname ="x$2x}' > pk.sql
db2 -tvf pk.sql | tee pk.sql.log
####以下示例显示NF的用法
db2 -x "select char(tbspace,20), char(index_tbspace,20) from syscat.tables where tabschema = 'EPRICER'" | sort | uniq > tbspaces.list
$ cat tbspaces.list
- -
DATATS_8K -
DATATS_8K INDXTS_8K
####awk’s built-in variable 'NF' which means 'Number of Fields'
cat tbspaces.list | awk '{ for(i=1; i<=NF; i++) print $i}' | tee list2
cat list2 | awk '{print "alter tablespace "$1" autoresize yes;"}' > autoresize.sql