awk 脚本同时解析多个文件
ARGC The number of command line arguments (does not include
options to gawk, or the program source). 命令行参数的个数
ARGIND The index in ARGV of the current file being processed. 命令行中文件序号
ARGV Array of command line arguments. The array is indexed
from 0 to ARGC - 1. Dynamically changing the contents
of ARGV can control the files used for data. 命令行参数数组
参考来源:https://blog.csdn.net/liuzhoulong/article/details/7879300
直接替代码(脚本名为parallel.awk):
1 BEGIN{ 2 print "HELLO!" 3 for(i=0;i<ARGC;i++) 4 { 5 print ARGV[i]; 6 } 7 } 8 { 9 if(ARGIND==1) 10 { 11 print "1_"$0; 12 } 13 else if(ARGIND ==2) 14 { 15 print "2_"$0; 16 } 17 else if(ARGIND==3) 18 { 19 print "3_"$0; 20 } 21 } 22 END{ 23 24 }
解析文件:
1.txt
1 a 2 b 3 c
2.txt
4 a 5 b 6 c
3.txt
7 a 8 b 9 c
执行awk脚本: awk -f parallel.awk 1.txt 2.txt 3.txt
结果如下:
HELLO! awk 1.txt 2.txt 3.txt 1_1 a 1_2 b 1_3 c 2_4 a 2_5 b 2_6 c 3_7 a 3_8 b 3_9 c
关于NR,FNR:当前文件的行号FNR;总的行号是NR。
斜杠互相替换:
gsub(/\\/,"/",str);
gsub("/","\\",info);
解析为sql语句的时候,经常会遇到单引号的问题:
printf("select * from acct where log_datetime between '\''2018-10-15 00:00:00'\'' and '\''2018-10-15 23:59:59'\'' and name in (%s);",str);
添加双引号: echo a,b,c,d | awk -F "," '{s="";for(i=1;i<=NF; ++i){if(1==i)s="\""$i"\"";else s=s",\""$i"\"";}print(s)}'