2017-07-25 107 views
1

我是新手,我确信这是一个愚蠢的问题,但我搜索了但没有找到答案。 我想选择2列我的文件2.我知道如何选择一列= $ 1和所有列= $ 0。但是如果我们只想在file3中显示2,3,... file2中的列,可能吗?awk比较2个文件,打印匹配并仅打印第二个文件的2列

awk -v RS='\r\n' 'BEGIN {FS=OFS=";"} FNR==NR {a[$2] = $1; next} {gsub(/_/,"-",$2);$2=toupper($2);print a[$2]?a[$2]:"NA",$0,a[$2]?a[$2]:"NA"}' $File2 $File1 > file3 

awk -v RS='\r\n' 'BEGIN {FS=OFS=";"} FNR==NR {a[$2] = $0; next} {gsub(/_/,"-",$2);$2=toupper($2);print a[$2]?a[$2]:"NA",$0,a[$2]?a[$2]:"NA"}' $File2 $File1 > file3 

我只想$ 1和$ 2的文件2,该代码doesn't工作。我获得一列数据从$ 1和$ 2

awk -v RS='\r\n' 'BEGIN {FS=OFS=";"} FNR==NR {a[$2] = $1$2; next} {gsub(/_/,"-",$2);$2=toupper($2);print a[$2]?a[$2]:"NA",$0,a[$2]?a[$2]:"NA"}' $File2 $File1 > file3 

任何解决方案?

+2

感谢您在这里展示您的努力。你可以在这里发布样例Input_file和期望的输出吗? – RavinderSingh13

回答

1
awk -v RS='\r\n' ' # call awk and set row separator 
     BEGIN { 
        FS=OFS=";"  # set input and output field separator 
     } 

     # Here you are reading first argument that is File2 
     FNR==NR { 
        # Save column2 and column3 separated by OFS that is ; 
        # from File2 which is first argument, in array a 
        # whose index/key being second field/column from File2 

        a[$2] = $2 OFS $3; 

        # Stop processing go to next line of File1 
        next 
     } 
     # Here on words you are reading second argument that is File1 
     { 
       # Global substitution 
       # replace _ with hyphen - in field2/column2 
       gsub(/_/,"-",$2); 

       # Uppercase field2/column2 
       $2=toupper($2); 

       # If field2 of current file (File1) exists in array a 
       # which is created above using File2 then 
       # print array value that is your field2 and field3 of File2 
       # else print "NA", and then output field separator, 
       # entire line/record of current file 

       print ($2 in a ? a[$2] : "NA"), $0 

     }' $File2 $File1 > file3 
+1

非常感谢,这正是我的问题。感谢您的解释,获得第二次支票总是很好! –

+0

@MarieDucourau欢迎您,祝你好运 –

相关问题