아래에 제공된 awk 스크립트를 설명해주세요.

아래에 제공된 awk 스크립트를 설명해주세요.

누구든지 아래에 작성된 AWK 스크립트를 단계별로 설명해 주시겠습니까?

플랫 파일 데이터의 형식을 지정하기 위해 스크립트에 다음 코드를 작성했습니다. 재사용할 수 있도록 알고 싶었습니다. 저는 UNIX 사용자는 아니지만 작업이 저에게 할당되었습니다. 도와주세요!

awk -vsep=$SEPARATOR 'NR>2{if(NF){if(!s){gsub(" *"sep"[ \t]*",sep);printf "%d%s\n",NR-2,$0}}else s=1}' file_name > new_file

 # where $SEPARATOR = ';'

미리 감사드립니다.

답변1

명령줄 옵션은 -vsep=$SEPERATORawk 변수 sep(검색/바꾸기에 사용됨)를 사용자가 지정하는 대로 설정합니다. ;당신의 경우에는.

# NR = Number of current Record, or line number
# Skip the first line
if ( NR > 2 ) {

  # NF = Number of fields in the current record
  # If the line contains something other than a blank line or the 
  # awk field separator characters (whitespace by default)
  if ( NF ) {

    # If we have not seen a blank line (script flag s)
    if ( !s ) {

      # Search the current line repeatedly (gsub) for any number of spaces (" *") 
      # before a ";" then any number of spaces or tabs ([ \t]*) after the `;`
      # and replace it all with just a ";"
      gsub( " *"sep"[ \t]*", sep );

      # Print the line number, 0 based (NR-2) as a signed decimal integer (`%d`)
      # then the complete line ($0) followed by a new line character (\n)
      printf "%d%s\n", NR-2, $0;
    }

  } else { 

    # Set the "seen a blank line" flag
    s = 1
  }

}

file_name > new_file이름이 지정된 새 파일에 출력을 씁니다.new_file

그런데 스크립트를 다음과 같이 구성하면 빈 줄 뒤에 데이터가 많으면 훨씬 읽기 쉽고 빨라질 것입니다.

awk -vsep=$SEPERATOR '{

# Skip the first line
if (NR == 1) { next; }

# Stop processing if we see a blank line
if (NF == 0) { exit; }

# Remove spaces before and spaces/tabs after separator
gsub( " *"sep"[ \t]*", sep );

# Print the line with a record number starting from 0
printf "%d%s\n", NR-2, $0;

}' file_name > new_file

관련 정보