awk打印特殊字符


 现在需要往oracle的一张表中新增10W行数据,执行插入的sql如下:

insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('18709737376', '2', to_date('19-10-2020', 'dd-mm-yyyy'), to_date('19-12-2021', 'dd-mm-yyyy'), '12-14 add');


插入的10W行数据只有第一列的值不同,其它都相同,第一列的值如下:

10W_Users.txt:

15209770454
13709789056
15003654216
15897026612
13519726991
...


 目前可以通过awk命令,拼接出10W条插入语句到sql脚本中,然后再通过sqlplus连接数据库,执行脚本,实现数据插入。

sql语句中包含 '等特殊字符,执行拼接时,需要将'进行转义:'\''。将语句分成三部分:insert前半+值+insert后半,具体命令如下:

awk '{print "insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('\'',"$1",'\'', '\''2'\'', to_date('\''19-10-2020'\'', '\''dd-mm-yyyy'\''), to_date('\''19-12-2021'\'', '\''dd-mm-yyyy'\''), '\''12-14 add'\'');"}' 10W_Users.txt > res.sql

 执行结果未能达到预期,号码前后存在空格

res.sql:

insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values (' 18309756168 ', '2', to_date('19-10-2020', 'dd-mm-yyyy'), to_date('19-12-2021', 'dd-mm-yyyy'), '12-14 add');
...

 如果把一个print语句拆分成三个print打印,就会打印换行:

awk '{print "insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('\''";print $1;print "'\'', '\''2'\'', to_date('\''19-10-2020'\'', '\''dd-mm-yyyy'\''), to_date('\''19-12-2021'\'', '\''dd-mm-yyyy'\''), '\''12-14 add'\'');"}' 10W_Users.txt > res.sql

res.sql:

insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('
13897199162
', '2', to_date('19-10-2020', 'dd-mm-yyyy'), to_date('19-12-2021', 'dd-mm-yyyy'), '12-14 add');
...



最终可行的方法:

print打印时,不要在三个需要拼接的子串间加任何字符,这样就能完整衔接。

awk '{print "insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('\''"$1"'\'', '\''2'\'', to_date('\''19-10-2020'\'', '\''dd-mm-yyyy'\''), to_date('\''19-12-2021'\'', '\''dd-mm-yyyy'\''), '\''12-14 add'\'');"}' 10W_Users.txt > res.sql

res.sql:

insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('18797349368', '2', to_date('19-10-2020', 'dd-mm-yyyy'),
 to_date('19-12-2021', 'dd-mm-yyyy'), '12-14 add');
...



如果想换成printf打印,命令如下:
\( 替换 (
\) 替换 )
'\''替换 '

awk --lint '{printf "%s%s%s\n", "insert into bd.rs_dcc_test_num (TEST_NUM, DEAL_FLAG, VALID_DATE, EXPIRE_DATE, DESCRIPTION) values ('\''",$1,"'\''2'\'', to_date('\''19-10-2020'\'', '\''dd-mm-yyyy'\''), to_date('\''19-12-2021'\'', '\''dd-mm-yyyy'\''), '\''12-14 add'\'');"}' 10W_Users.txt > res.sql

--lint选项是为了去除printf打印的警告信息(使用了跳脱字符):

awk '{printf "%s\n", "just test\(\)"}' A.txt

# 警告信息如下
awk: cmd. line:1: warning: escape sequence `\(' treated as plain `('
awk: cmd. line:1: warning: escape sequence `\)' treated as plain `)'
just test()

你可能感兴趣的:(linux,命令,awk,printf,print,打印特殊字符)