Awk-두 파일 간의 일치 값
Dec 28 2020
비교하려는 두 개의 파일이 있으며 두 파일 모두에서 존재하는 데이터로 final.txt 파일을 만듭니다.
File1-열 1 및 File2-열 2에는 두 파일간에 일치해야하는 값이 포함되어 있습니다.
그래서 본질적으로 저는-> file1에서 column1을 가져 오려고합니다. file2의 column2에 일치하는 항목이있는 경우 File1Column1, File1Column2 및 File2Column1을 final.txt라는 새 파일에 씁니다.
예
파일 1
1000,Brian
1010,Jason
400,Nick
파일 2
3044 "1000"
4466 "400"
1206 "1010"
다음과 같은 출력 파일
1000,Brian,3044
1010,Jason,1206
400,Nick,4466
내 테스트 코드에 결과가 표시되지 않음
awk -F"[,]" 'NR==FNR{a[$1]=$1","$2;next} ($2 in a){print a[$2]","$1}' file1.txt file2.txt
나는 내가 awk로 이것을 할 수 있어야한다고 믿지만, 어떤 이유로 나는 이것을 정말로 고군분투하고있다. 어떤 도움이라도 대단히 감사하겠습니다.
감사
답변
2 RavinderSingh13 Dec 28 2020 at 00:58
GNU에 표시된 샘플을 따라 작성하고 테스트 해 보시기 바랍니다 awk
.
awk '
FNR==NR{
gsub(/"/,"",$2) arr[$2]=$1 next } FNR==1{ FS="," OFS="," $0=$0 } ($1 in arr){
print $0,arr[$1]
}
' Input_file2 Input_file1
설명 : 위에 대한 자세한 설명을 추가합니다.
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
gsub(/"/,"",$2) ##globally substituting " in 2nd field with NULL. arr[$2]=$1 ##Creating array arr with index of 2nd field and value of 1st field. next ##next will skip all further statements from here. } FNR==1{ ##Checking condition if this is first line of Input_file1. FS="," ##Setting FS as comma here. OFS="," ##Setting OFS as comma here. $0=$0 ##Reassigning current line to itself so that field separator values will be implemented to current line. } ($1 in arr){ ##Checking condition if 1st field is present in arr then do following.
print $0,arr[$1] ##Printing current line and value of array arr.
}
' file2 file1 ##Mentioning Input_file names here.
EdMorton Dec 28 2020 at 05:09
샘플 입력 / 출력에서 2 개의 입력 파일 사이에 일치하지 않는 행을 포함하지 않았으므로 이러한 경우에 원하는 작업을 수행하거나 수행하지 않을 수 있습니다.
$ cat tst.awk BEGIN { FS="[[:space:]\",]+"; OFS="," } NR==FNR { map[$2] = $1 next } { print $0, map[$1] }
$ awk -f tst.awk file2 file1
1000,Brian,3044
1010,Jason,1206
400,Nick,4466