2017-10-13 29 views

回答

1
awk 'FNR > 1 && dateA <= $5 ' FS='|' dateA="$dateA" "$infile" 
  • FNR是可变的,为您提供了记录总数,涉及到当前文件,不要混淆与可变NRFNRNR值将是相同的,只要awk读取第一个文件,对于第二个文件,变量FNR将重置,而NR不会。

这是怎么FNRNR作品awk

$ seq 1 5 >file1 
$ seq 1 3 >file2 
$ cat file1 
1 
2 
3 
4 
5 

$ cat file2 
1 
2 
3 

$ awk '{print "Current line : "$0,"File: "FILENAME,"FNR : ",FNR,"NR : ",NR}' file1 file2 
Current line : 1 File: file1 FNR : 1 NR : 1 
Current line : 2 File: file1 FNR : 2 NR : 2 
Current line : 3 File: file1 FNR : 3 NR : 3 
Current line : 4 File: file1 FNR : 4 NR : 4 
Current line : 5 File: file1 FNR : 5 NR : 5 
Current line : 1 File: file2 FNR : 1 NR : 6 
Current line : 2 File: file2 FNR : 2 NR : 7 
Current line : 3 File: file2 FNR : 3 NR : 8 
  • FNR > 1 && dateA <= $5如果没有记录读取大于1和可变dateA小于或等于5场/列,我们得到布尔真实状态,所以这样的行将被打印

  • FS='|'FS是输入分隔符,你也可以把它像

    • awk -F'|' '{ .... }'
    • awk -v FS='|' '{ .... }'
    • awk 'BEGIN{FS="|"}{ .... }'
  • dateA="$dateA"dateAawk变量,其值是从你的shell变量$dateA采取,同样你可以设置它像

    • awk -v dateA="$dateA" '{ .... }'

你上面的命令可以写成像下面还

awk -F'|' -v dateA="$dateA" 'FNR>1 && dateA <= $5' "$infile" 

,有些人喜欢awk 'condition{action}'更好的阅读,所以你也可以把它写成

awk -F'|' -v dateA="$dateA" 'FNR>1 && dateA <= $5{ print }' "$infile" 
            ^    ^
            |     | 
          If this condition is true | 
                 | 
            Action is to print line, 
            print or print $0 is same 
0

AWK允许与形式var=value分配在参数内部变量。由于AWK无权访问shell变量dateA="$dateA"用于将dateA“导出”为AWK脚本。

注意,文件处理过程中发生的分配参数,BEGIN后,可在中间文件中使用:

$ echo >file1; echo >file2 
$ awk -vx=0 ' 
     BEGIN { 
       print "BEGIN", x 
     } 
     { 
       print FILENAME, x 
     } 
     END { 
       print "END", x 
     }' x=1 file1 x=2 file2 x=3 
BEGIN 0 
file1 1 
file2 2 
END 3 
1

请通过下面的解释,让我知道,如果这可以帮助你。

说明:请不要在awk之后运行,它仅作解释之用。

awk ' 
FNR>1 && dateA<=$5 ##FNR denotes the number of current line in awk so here 2 conditions with AND conditions are being checked. 
        ##1st is if current line number is greater than 1 and second is variable named dateA value should be lesser 
        ##and equal to 5. 
        ##So let me explain here awk works on method of condition and then action, so if any condition is TRUE then action 
        ##will happen, here condition is there but NO action defined, so by default print action will happen. print of 
        ##current line. 
' 
FS='|'    ##FS denotes the field separator, in awk we could define the field separator by ourselves too, so making it here as | 
dateA="$dateA"  ##creating variable named dateA whose value is equal to shell variable named dateA. In awk if we have to assign 
        ##shell variable values to awk variables we have to create an awk variable and then assign shell variable value to 
        ##it. 
"$infile"   ##Mentioning the Input_file name here which awk has to go through. Point to be noted here the "$infile" means 
        ##it is a shell variable (as we all know to print shell variable value we have to use "$infile")