![아래에 제공된 awk 스크립트를 설명해주세요.](https://linux55.com/image/36273/%EC%95%84%EB%9E%98%EC%97%90%20%EC%A0%9C%EA%B3%B5%EB%90%9C%20awk%20%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%A5%BC%20%EC%84%A4%EB%AA%85%ED%95%B4%EC%A3%BC%EC%84%B8%EC%9A%94..png)
누구든지 아래에 작성된 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=$SEPERATOR
awk 변수 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