2014-12-01 3 views

답변

3
-F, 

필드 분할을 위해 FS에서 ,으로 설정하십시오.

NR==FNR{a[$2]=$0;next} 

현재 처리 된 라인 번호 (NR)는 현재의 파일 번호의 라인 (FNR)

동일하다 (즉, 최초의 비어 있지 않은 파일을 처리 할 때). 입력 라인을 라인의 두 번째 필드 ( $2)의 키 아래 a 어레이에 저장하고 다음 라인 처리 ( next)로 건너 뜁니다.

$2 in a{ print a[$2],$4, $5 } 

전류 선 ($2)의 두번째 필드는 현재 라인의 필드에 네 OFS (쉼표)이어서이 키 a[$2] 아래 어레이로부터 필드 ($4 배열 a 인쇄 중일 때) 다음에 현재 줄 ($5)의 필드 5가 이어지는 OFS이옵니다. 입력 파일을 처리하기 전에 행 ,

OFS=, 

세트 OFS.

tl; dr file2.csv의 열 4와 5를 일치하는 줄 (필드 2 기준)에 file1.csv에서 추가하십시오.

3
-F,   # Set the field separator to a comma 

NR==FNR  # Test if we are looking the first file 
      # NR is incremented for every line read across all input files 
      # FNR is incremented for every line read in current file and resets to 0 
      # The only time NR==FNR is when we are looking at the first file 

a[$2]=$0  # Create a lookup for the line based on the value in the 2nd column 

next   # Short circuit the script and get the next input line 

$2 in a  # If we are here we are looking at the second file 
      # Check if we have seen the second field in the first file 

a[$2],$4,$5 # Print the whole matching line from the first file 
      # with the 4th & 5th fields from the second 

OFS=,  # Separate the output with a comma 
+1

wrt'오직 NR == FNR은 첫 번째 파일을보고있을 때입니다 .' 또는 두 번째 파일을보고 첫 번째 파일이 비어있는 경우입니다. 사람들을 가끔씩 방문하는 것을 잊지 마세요. –

+1

@EdMorton은'ARGIND == 1'을 사용하고 두 개의 문자를 잃어 버리는 것이 더 좋다. –

+0

@Jidder 그것은 GNU에 특화된 것이지만 예, gawk에게는 좋은 해결책이다. 비 gawks에 대해'FNR == 1 {ARGIND ++}'를 추가 할 수 있지만 빈 파일에서는 실패합니다. 'FILENAME == ARGV [1]'을 사용할 수도 있지만 파일 이름 영역에 변수를 설정하면 실패합니다 (그렇게하지 않는 이유가 하나 더 있습니다!). 'NR == FNR'은 보통 괜찮습니다. 첫 번째 파일이 비어 있으면 실패 할 것이라는 점을 명심하십시오. –

관련 문제