读取作为参数传递给AWK脚本的3个分隔文件,并解析3个文件并存储在3个不同的数组中

问题描述 投票:0回答:2

档案1:

A|sam|2456|8901

B|kam|5678|9000

C|pot|4567|8000

文件2:

X|ter|2456|8901

Y|mar|5678|9000

Z|poi|4567|8000

档案3:

Column1|Column2|Column3|Coumn4

现在我想将这3个文件作为参数传递给GNU Awk脚本,如下所示 -

awk -f script.awk file1 file2 file3

我写的脚本只能处理2个文件但不能处理第3个文件。请求帮助。


script.awk

BEGIN     { # setup file separator and sorting:
        FS=OFS="|" 
        PROCINFO["sorted_in"]="@ind_str_asc"
      }

# skip header lines
FNR == 1  { next }

# store first file
(FNR==NR) { f1[$5]=$0
            # skip processing of other rules and 
            # read the next line from input
            next
         }

# store second file
          { f2[$5]=$0
            if( ! ($5 in f1)) {
                f1[$5] = ""
            }
         }

END       { 
        for( k in f1) {
            split( f1[k], arr1, "|")

            for( c = 1; c <= length( f1[ k ] ); c++ ) {
                    print arr1[c]
                }
            }
         for( k in f2) {

            split( f2[k], arr2, "|")
            for( c = 1; c <= length( f2[ k ] ); c++ ) {
                    print arr2[c]
                }
            }
        }
      }

我的目标是在打印中的相同代码中读取第三个文件,其方式与在上面的代码中处理打印的方式类似。

注意:如果任何人都可以保持与上面类似的代码结构并且只包括第三个文件的读取和打印,那将会很好。

bash shell awk
2个回答
1
投票

您现有的代码比以前更复杂。它可以写成:

BEGIN     { # setup file separator and sorting:
    ...
      }

# skip header lines
FNR == 1  { next }

ARGIND==1 { f1[$5]=$0; next }
ARGIND==2 { f2[$5]=$0; f1[$5] }

END       { 
    ...
      }

我假设您可以看到添加第3个文件的明显扩展名。上面要求你已经使用的ARGIND和PROCINFO []的GNU awk。


1
投票

您可以使用ARGV数组来处理多个文件,如下所示:

function disp() {
   for (i=1; i<=NF; i++)
      print FILENAME " :: " FNR " :: " $i
   print ""
}

BEGIN { # setup file separator and sorting:
   FS=OFS="|" 
   PROCINFO["sorted_in"]="@ind_str_asc"
}

# process first file
ARGV[1] == FILENAME {
   disp()
}
# process second file
ARGV[2] == FILENAME {
   disp()
}
# process third file
ARGV[3] == FILENAME {
   disp()
}
© www.soinside.com 2019 - 2024. All rights reserved.