awk 명령어 (AIX 5.3·6.1)
https://archive.horanglab.com/posts/aix-cmd-awk
핵심 정리
- 파일을 한 줄(레코드)씩 읽어 확장 정규 표현식(ERE)과 비교하고, 맞는 줄에 지정한 동작을 합니다. 프로그램은
패턴 { 동작 }형태입니다. - 필드는 기본으로 공백·탭으로 나뉘며
$1,$2, …, 줄 전체는$0입니다. 구분자는-F나FS변수로 바꿉니다. BEGIN은 첫 레코드를 읽기 전에,END는 모든 입력을 읽은 뒤에 실행합니다.- 패턴은 정규 표현식(
/smi/), 관계식($1 > 100), 범위(/begin/,/end/), 불 결합(&&,||,!)으로 씁니다. - 내장 함수:
length,substr,index,split,sub,gsub,match,sprintf,tolower,toupper,getline,system,close등. AIX에는 바이트 길이를 돌려주는blength도 있습니다. - 자주 쓰는 특수 변수:
NR(레코드 번호),NF(필드 수, 최대 99),FS·OFS,RS·ORS,FILENAME,ENVIRON. - 6.1에서
-u(출력 버퍼 없음)가 생겼습니다.
| 항목 | 내용 |
|---|---|
| 버전 | AIX 5.3, AIX 6.1 (6.1에서 -u 플래그가 더해짐) |
| 원문 | IBM Commands Reference — 5.3 Volume 1, 6.1 Volume 1 |
| 파일 | /usr/bin/awk |
| 관련 명령어 | grep, egrep, sed, lex, bc, printf |
목적
파일에서 패턴과 맞는 줄을 찾아, 그 줄에 지정한 동작을 합니다.
영어 원문
Finds lines in files that match a pattern and performs specified actions on those lines.
구문
awk [ -u ] [ -F Ere ] [ -v Assignment ] ... { -f ProgramFile | 'Program' } [ [ File ... | Assignment ... ] ] ...
-u는 6.1 구문에만 있습니다.
설명
awk 명령은 사용자가 준 명령 모음을 써서 파일들을 한 줄씩 사용자가 준 확장 정규 표현식과 비교합니다. 그리고 확장 정규 표현식과 맞는 줄마다 동작을 합니다.
awk의 패턴 검색은 grep 명령보다 일반적이며, 입력 줄 하나에 여러 동작을 할 수 있습니다. awk 프로그래밍 언어는 컴파일할 필요가 없고, 변수, 숫자 함수, 문자열 함수, 논리 연산자를 쓸 수 있습니다.
awk 명령은 LANG, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_NUMERIC, NLSPATH, PATH 환경 변수의 영향을 받습니다.
영어 원문
The awk command uses a set of user-supplied instructions to compare a set of files, one line at a time, to extended regular expressions supplied by the user. Then actions are performed upon any line that matches the extended regular expressions.
The pattern searching of the awk command is more general than that of the grep command, and it allows the user to perform multiple actions on input text lines. The awk command programming language requires no compiling, and allows the user to use variables, numeric functions, string functions, and logical operators.
The awk command is affected by the LANG, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_NUMERIC, NLSPATH, and PATH environment variables.
The following topics are covered in this article:
Input for the awk Command
Output for the awk Command
File Processing with Records and Fields
The awk Command Programming Language – Patterns – Actions – Variables – Special Variables
Flags
Examples
awk의 입력
awk 명령은 입력 텍스트 파일과 프로그램 명령, 두 가지 입력을 받습니다.
입력 텍스트 파일
검색과 동작은 입력 텍스트 파일에 대해 이뤄집니다. 파일은 다음 방법으로 정합니다.
- 명령줄에 File 변수를 지정합니다.
- 특수 변수
ARGV와ARGC를 바꿉니다. - File 변수가 없으면 표준 입력을 줍니다.
File 변수로 파일을 여러 개 지정하면 지정한 순서대로 처리합니다.
프로그램 명령
awk의 동작은 사용자가 준 명령이 정합니다. 명령은 명령줄의 'Program' 변수나, -f 플래그와 ProgramFile 변수로 지정한 파일에서 옵니다. 프로그램 파일을 여러 개 지정하면 지정한 순서대로 이어 붙인 명령을 씁니다.
영어 원문
The awk command takes two types of input: input text files and program instructions.
Input Text Files
Searching and actions are performed on input text files. The files are specified by:
Specifying the File variable on the command line.
Modifying the special variables ARGV and ARGC.
Providing standard input in the absence of the File variable.
If multiple files are specified with the File variable, the files are processed in the order specified.
Program Instructions
Instructions provided by the user control the actions of the awk command. These instructions come from either the 'Program' variable on the command line or from a file specified by the -f flag together with the ProgramFile variable. If multiple program files are specified, the files are concatenated in the order specified and the resultant order of instructions is used.
awk의 출력
awk 명령은 입력 텍스트 파일의 데이터로 세 가지 출력을 만듭니다.
- 고른 데이터를 입력 파일을 바꾸지 않고 표준 출력에 씁니다.
- 입력 파일의 고른 부분을 바꿉니다.
- 고른 데이터를 바꿔 표준 출력에 쓰며, 이때 입력 파일의 내용은 바꿀 수도 있고 그대로 둘 수도 있습니다.
이 출력은 모두 같은 파일에 대해 할 수 있습니다. awk의 프로그래밍 언어로 출력을 재지정할 수 있습니다.
영어 원문
The awk command produces three types of output from the data within the input text file:
Selected data can be printed to standard output, without alteration to the input file.
Selected portions of the input file can be altered.
Selected data can be altered and printed to standard output, with or without altering the contents of the input file.
All of these types of output can be performed on the same file. The programming language recognized by the awk command allows the user to redirect output.
레코드와 필드로 파일 처리하기
파일은 다음 순서로 처리합니다.
- 명령을 훑어 입력 파일을 읽기 전에 하도록 지정한 동작을 실행합니다.
awk언어의BEGIN문으로 첫 레코드를 읽기 전에 할 명령을 지정합니다. 특수 변수를 초기화할 때 특히 좋습니다. - 입력 파일에서 레코드 하나를 읽습니다. 레코드는 레코드 구분자로 나뉜 데이터 묶음입니다. 레코드 구분자의 기본값은 줄바꿈 문자라서 파일의 한 줄이 한 레코드가 됩니다. 레코드 구분자는 특수 변수
RS로 바꿉니다. - 레코드를 명령에 지정한 패턴마다 비교합니다. 레코드 안의 특정 필드를 비교하게 할 수도 있습니다. 필드는 기본으로 공백(빈칸이나 탭)으로 나뉘며, 필드마다 필드 변수로 가리킵니다. 첫 필드는
$1, 둘째 필드는$2, 이런 식이고 레코드 전체는$0입니다. 필드 구분자는 명령줄의-F플래그나 특수 변수FS로 바꿉니다.FS에는 공백, 문자 하나, 확장 정규 표현식을 쓸 수 있습니다. - 레코드가 패턴과 맞으면 그 패턴에 딸린 동작을 레코드에 합니다.
- 레코드를 모든 패턴과 비교하고 지정한 동작을 모두 하면 다음 레코드를 읽습니다. 입력 파일의 레코드를 모두 읽을 때까지 되풀이합니다.
- 입력 파일이 여럿이면 다음 파일을 열어 모든 입력 파일을 읽을 때까지 되풀이합니다.
- 마지막 파일의 마지막 레코드를 읽은 뒤, 입력 처리 다음에 하도록 지정한 명령을 실행합니다.
END문으로 마지막 레코드를 읽은 뒤에 할 동작을 지정합니다.awk가 한 일을 알리는 메시지를 낼 때 특히 좋습니다.
영어 원문
Files are processed in the following way:
The awk command scans its instructions and executes any actions specified to occur before the input file is read. The BEGIN statement in the awk programming language allows the user to specify a set of instructions to be done before the first record is read. This is particularly useful for initializing special variables.
One record is read from the input file. A record is a set of data separated by a record separator. The default value for the record separator is the new-line character, which makes each line in the file a separate record. The record separator can be changed by setting the RS special variable.
The record is compared against each pattern specified by the awk command's instructions. The command instructions can specify that a specific field within the record be compared. By default, fields are separated by white space (blanks or tabs). Each field is referred to by a field variable. The first field in a record is assigned the
$1variable, the second field is assigned the$2variable, and so forth. The entire record is assigned to the$0variable. The field separator can be changed by using the-Fflag on the command line or by setting the FS special variable. The FS special variable can be set to the values of: blank, single character, or extended regular expression.If the record matches a pattern, any actions associated with that pattern are performed on the record.
After the record is compared to each pattern, and all specified actions are performed, the next record is read from input; the process is repeated until all records are read from the input file.
If multiple input files have been specified, the next file is then opened and the process repeated until all input files have been read.
After the last record in the last file is read, the awk command executes any instructions specified to occur after the input processing. The END statement in the awk programming language allows the user to specify actions to be performed after the last record is read. This is particularly useful for sending messages about what work was accomplished by the awk command.
awk 프로그래밍 언어
awk 프로그래밍 언어는 다음 형태의 문장으로 이뤄집니다.
Pattern { Action }
레코드가 지정한 패턴과 맞거나 패턴과 맞는 필드를 담고 있으면, 딸린 동작을 합니다. 동작 없이 패턴만 지정하면 패턴을 담은 줄 전체를 표준 출력에 씁니다. 패턴 없이 동작만 지정하면 모든 입력 레코드에 그 동작을 합니다.
영어 원문
The awk command programming language consists of statements in the form:
Pattern
If a record matches the specified pattern, or contains a field which matches the pattern, the associated action is then performed. A pattern can be specified without an action, in which case the entire line containing the pattern is written to standard output. An action specified without a pattern is performed for every input record.
패턴
awk 언어의 패턴은 정규 표현식, 관계식, 패턴 결합, BEGIN·END 패턴의 네 가지입니다.
정규 표현식
awk가 쓰는 확장 정규 표현식은 grep이나 egrep 명령의 것과 비슷합니다. 가장 간단한 형태는 슬래시로 감싼 문자열입니다. 예를 들어 testfile의 내용이 다음과 같다고 합시다.
smawley, andy
smiley, allen
smith, alan
smithern, harry
smithhern, anne
smitters, alexis
다음 명령은 smi가 들어 있는 레코드를 모두 표준 출력에 씁니다. 여기서 프로그램 '/smi/'는 동작이 없는 패턴입니다.
awk '/smi/' testfile
smiley, allen
smith, alan
smithern, harry
smithhern, anne
smitters, alexis
확장 정규 표현식에 쓰는 특수 문자는 다음과 같습니다(예는 모두 위 testfile 기준).
| 문자 | 뜻 | 예 | 출력 |
|---|---|---|---|
+ |
앞의 문자나 식이 한 번 이상 | awk '/smith+ern/' testfile |
smithern, harry, smithhern, anne |
? |
앞의 문자나 식이 없거나 한 번 | awk '/smith?/' testfile |
smith, alan, smithern, harry, smithhern, anne, smitters, alexis |
| 세로 막대 | 양쪽 문자열 중 하나 | awk '/allen|alan/' testfile |
smiley, allen, smith, alan |
( ) |
문자열을 묶음 | awk '/a(ll)?(nn)?e/' testfile |
smiley, allen, smithhern, anne |
{m} |
정확히 m번 | awk '/l{2}/' testfile |
smiley, allen |
{m,} |
적어도 m번 | awk '/t{2,}/' testfile |
smitters, alexis |
{m,n} |
m번 이상 n번 이하(m은 n 이하) | awk '/er{1,2}/' testfile |
smithern, harry, smithhern, anne, smitters, alexis |
[String] |
대괄호 안의 문자 중 하나 | awk '/sm[a-h]/' testfile |
smawley, andy |
[^String] |
대괄호 안의 문자가 아닌 것 | awk '/sm[^a-h]/' testfile |
smiley, allen 외 4줄 |
~, !~ |
변수가 정규 표현식과 맞음(~), 맞지 않음(!~) |
awk '$1 ~ /n/' testfile |
smithern, harry, smithhern, anne |
^ |
필드나 레코드의 시작 | awk '$2 ~ /^h/' testfile |
smithern, harry |
$ |
필드나 레코드의 끝 | awk '$2 ~ /y$/' testfile |
smawley, andy, smithern, harry |
. |
끝의 줄바꿈 문자를 뺀 아무 문자 하나 | awk '/a..e/' testfile |
smawley, andy, smiley, allen, smithhern, anne |
* |
앞의 것이 0번 이상(.*는 아무 문자 0개 이상) |
awk '/a.*e/' testfile |
smawley, andy, smiley, allen, smithhern, anne, smitters, alexis |
\ |
이스케이프 문자. 뒤 문자의 특별한 뜻을 없앰 | /a\/\// |
a//와 맞음 |
- 세로 막대 줄의 예는 표 안이라
|(전각)로 적었습니다. 실제로는awk '/allen|alan/' testfile처럼 씁니다. - 백슬래시 자체를 문자로 쓰려면 백슬래시 두 개를 씁니다.
인식하는 이스케이프 시퀀스
awk는 C 언어 관례의 이스케이프 시퀀스 대부분과, awk가 특수 문자로 쓰는 몇 가지를 인식합니다.
| 시퀀스 | 나타내는 문자 |
|---|---|
\" |
큰따옴표 |
\/ |
슬래시 |
\ddd |
1~3자리 8진수(d)로 나타낸 인코딩의 문자 |
\\ |
백슬래시 |
\a |
경고(벨) 문자 |
\b |
백스페이스 |
\f |
폼 피드 |
\n |
줄바꿈(아래 참고) |
\r |
캐리지 리턴 |
\t |
탭 |
\v |
세로 탭 |
참고: gsub, match, split, sub 내장 함수를 빼면, 확장 정규 표현식 비교는 입력 레코드를 단위로 합니다. 레코드 구분자 문자(기본은 줄바꿈)는 식 안에 넣을 수 없고, 어떤 식도 레코드 구분자와 맞지 않습니다. 레코드 구분자가 줄바꿈이 아니면 줄바꿈과 맞을 수 있습니다. 위 네 함수에서는 텍스트 문자열을 단위로 비교하므로 레코드 구분자를 포함한 어떤 문자든 패턴에 넣을 수 있습니다. 다만 어느 경우든 패턴에 NULL 문자를 넣으면 결과가 정의되지 않습니다.
관계식
관계 연산자 <(작음), >(큼), <=(작거나 같음), >=(크거나 같음), ==(같음), !=(같지 않음)로 패턴을 만들 수 있습니다.
| 패턴 | 맞는 레코드 |
|---|---|
$1 < $4 |
첫 필드가 넷째 필드보다 작은 레코드 |
$1 != "q" |
첫 필드가 q가 아닌 레코드 |
$1 >= "d" |
대조 값으로 비교. 원문은 "첫 필드가 a, b, c, d로 시작하는 레코드"라고 설명합니다(아래 원문과 다른 점 참고). |
관계 연산자는 문자열 값에도 쓸 수 있습니다. 다른 정보가 없으면 필드 변수는 문자열 값으로 비교합니다.
패턴 결합
- 범위: 패턴 두 개를
,(쉼표)로 나눠 지정합니다. 첫 패턴과 맞는 레코드부터 둘째 패턴과 맞는 레코드까지(둘째 포함) 동작을 합니다. 예를 들어/begin/,/end/는begin이 든 레코드부터end가 든 레코드까지 맞습니다. - 괄호:
( )로 패턴을 묶습니다. - 불 연산자:
||(또는),&&(그리고),!(아님)로 패턴을 식으로 결합하며, 식이 참이면 맞습니다. 예를 들어$1 == "al" && $2 == "123"은 첫 필드가al이고 둘째 필드가123인 레코드와 맞습니다.
BEGIN과 END 패턴
BEGIN 패턴의 동작은 입력을 읽기 전에, END 패턴의 동작은 모든 입력을 읽은 뒤에 합니다. BEGIN과 END는 여러 개 쓸 수 있고 지정한 순서대로 처리합니다. 프로그램 안에서 END가 BEGIN보다 앞에 와도 됩니다. 프로그램이 BEGIN 문만 있으면 동작만 하고 입력은 읽지 않습니다. END 문만 있으면 동작하기 전에 입력을 모두 읽습니다.
영어 원문
There are four types of patterns used in the awk command language syntax:
Regular Expressions
Relational Expressions
Combinations of Patterns
BEGIN and END Patterns.
Regular Expressions
The extended regular expressions used by the awk command are similar to those used by the grep or egrep command. The simplest form of an extended regular expression is a string of characters enclosed in slashes. For an example, suppose a file named testfile had the following contents: smawley, andy smiley, allen smith, alan smithern, harry smithhern, anne smitters, alexis
Entering the following command line: awk ’/smi/’ testfile
would print to standard output of all records that contained an occurrence of the string smi. In this example, the program '/smi/' for the awk command is a pattern with no action. The output is: smiley, allen smith, alan smithern, harry smithhern, anne smitters, alexis
The following special characters are used to form extended regular expressions:
Character Function + Specifies that a string matches if one or more occurrences of the character or extended regular expression that precedes the + (plus) are within the string. The command line:
awk ’/smith+ern/’ testfile
prints to standard output any record that contained a string with the characters smit, followed by one or more h characters, and then ending with the characters ern. The output in this example is:
smithern, harry
smithhern, anne
? Specifies that a string matches if zero or one occurrences of the character or extended regular expression that precedes the ? (question mark) are within the string. The command line:
awk ’/smith?/’ testfile
prints to standard output of all records that contain the characters smit, followed by zero or one instance of the h character. The output in this example is:
smith, alan
smithern, harry
smithhern, anne
smitters, alexis
| Specifies that a string matches if either of the strings separated by the | (vertical line) are within the string. The command line:
awk ’/allen
|
alan /’ testfile
prints to standard output of all records that contained the string allen or alan. The output in this example is:
smiley, allen
smith, alan
Character Function ( ) Groups strings together in regular expressions. The command line:
awk ’/a(ll)?(nn)?e/’ testfile
prints to standard output of all records with the string ae or alle or anne or allnne. The output in this example is:
smiley, allen
smithhern, anne
Specifies that a string matches if exactly m occurrences of the pattern are within the string. The command line:
awk ’/l{2}/’ testfile
prints to standard output
smiley, allen
{m,} Specifies that a string matches if at least m occurrences of the pattern are within the string. The command line:
awk ’/t{2,}/’ testfile
prints to standard output:
smitters, alexis
{m, n} Specifies that a string matches if between m and n, inclusive, occurrences of the pattern are within the string ( where m <= n). The command line:
awk ’/er{1, 2}/’ testfile
prints to standard output:
smithern, harry
smithern, anne
smitters, alexis
[String] Signifies that the regular expression matches any characters specified by the String variable within the square brackets. The command line:
awk ’/sm[a-h]/’ testfile
prints to standard output of all records with the characters sm followed by any character in alphabetical order from a to h. The output in this example is:
smawley, andy
[^ String] A ^ (caret) within the [ ] (square brackets) and at the beginning of the specified string indicates that the regular expression does not match any characters within the square brackets. Thus, the command line:
awk ’/sm[^a-h]/’ testfile
prints to standard output:
smiley, allen
smith, alan
smithern, harry
smithhern, anne
smitters, alexis
,! Signifies a conditional statement that a specified variable matches (tilde) or does not match (tilde, exclamation point) the regular expression. The command line:
awk ’$1 ~ /n/’ testfile
prints to standard output of all records whose first field contained the character n. The output in this example is:
smithern, harry
smithhern, anne
^ Signifies the beginning of a field or record. The command line:
awk ’$2 ~ /^h/’ testfile
prints to standard output of all records with the character h as the first character of the second field. The output in this example is:
smithern, harry
Character Function $ Signifies the end of a field or record. The command line:
awk ’$2 ~ /y$/’ testfile
prints to standard output of all records with the character y as the last character of the second field. The output in this example is:
smawley, andy
smithern, harry
. (period) Signifies any one character except the terminal new-line character at the end of a space. The command line:
awk ’/a..e/’ testfile
prints to standard output of all records with the characters a and e separated by two characters. The output in this example is:
smawley, andy
smiley, allen
smithhern, anne
*(asterisk) Signifies zero or more of any characters. The command line:
awk ’/a.*e/’ testfile
prints to standard output of all records with the characters a and e separated by zero or more characters. The output in this example is:
smawley, andy
smiley, allen
smithhern, anne
smitters, alexis
\ (backslash) The escape character. When preceding any of the characters that have special meaning in extended regular expressions, the escape character removes any special meaning for the character. For example, the command line:
/a\/\//
would match the pattern a //, since the backslashes negate the usual meaning of the slash as a delimiter of the regular expression. To specify the backslash itself as a character, use a double backslash. See the following item on escape sequences for more information on the backslash and its uses.
Recognized Escape Sequences
The awk command recognizes most of the escape sequences used in C language conventions, as well as several that are used as special characters by the awk command itself. The escape sequences are:
Escape Sequence Character Represented \" \" (double-quotation) mark \/ / (slash) character \ddd Character whose encoding is represented by a one-, two- or three-digit octal integer, where d represents an octal digit \\ \ (backslash) character \a Alert character \b Backspace character \f Form-feed character \n New-line character (see following note) \r Carriage-return character \t Tab character \v Vertical tab.
Note: Except in the gsub, match, split, and sub built-in functions, the matching of extended regular expressions is based on input records. Record-separator characters (the new-line character by default) cannot be embedded in the expression, and no expression matches the record-separator character. If the record separator is not the new-line character, then the new-line character can be matched. In the four built-in functions specified, matching is based on text strings, and any
character (including the record separator) can be embedded in the pattern so that the pattern matches the appropriate character. However, in all regular-expression matching with the awk command, the use of one or more NULL characters in the pattern produces undefined results.
Relational Expressions
The relational operators < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), = = (equal to), and ! = (not equal to) can be used to form patterns. For example, the pattern: $1 < $4
matches records where the first field is less than the fourth field. The relational operators also work with string values. For example: $1 =! "q"
matches all records where the first field is not a q. String values can also be matched on collation values. For example: $1 >= "d"
matches all records where the first field starts with a character that is a, b, c, or d. If no other information is given, field variables are compared as string values.
Combinations of Patterns
Patterns can be combined using three options:
- Ranges are specified by two patterns separated with a , (comma). Actions are performed on every record starting with the record that matches the first pattern, and continuing through and including the record that matches the second pattern. For example:
/begin/,/end/
matches the record containing the string begin, and every record between it and the record containing the string end, including the record containing the string end.
Parentheses ( ) group patterns together.
The boolean operators
||(or), && (and), and ! (not) combine patterns into expressions that match if they evaluate true, otherwise they do not match. For example, the pattern:$1 == "al" && $2 == "123"
matches records where the first field is al and the second field is 123.
BEGIN and END Patterns
Actions specified with the BEGIN pattern are performed before any input is read. Actions specified with the END pattern are performed after all input has been read. Multiple BEGIN and END patterns are allowed and processed in the order specified. An END pattern can precede a BEGIN pattern within the program statements. If a program consists only of BEGIN statements, the actions are performed and no input is read. If a program consists only of END statements, all the input is read prior to any actions being taken.
동작
동작 문에는 일반 동작 문, 내장 함수, 사용자 정의 함수, 조건문, 출력 문이 있습니다.
동작 문
동작 문은 { }(중괄호)로 감쌉니다. 패턴 없이 지정하면 모든 레코드에 합니다. 중괄호 안에 동작을 여러 개 쓸 수 있으며, 줄바꿈이나 ;(세미콜론)으로 나누고 나온 순서대로 처리합니다.
| 종류 | 형태와 설명 |
|---|---|
| 산술 | +(더하기), -(빼기), /(나누기), ^(거듭제곱), *(곱하기), %(나머지)를 Expression Operator Expression 형태로 씁니다. $2 = $1 ^ 3은 첫 필드의 세제곱을 둘째 필드에 넣습니다. |
| 단항 | 단항 -, +는 C 언어처럼 동작합니다(+Expression, -Expression). |
| 증가·감소 | 전위 ++Variable, --Variable과 후위 Variable++, Variable--가 C 언어처럼 동작합니다. |
| 대입 | +=, -=, /=, *=가 C 언어처럼 동작합니다. $1 *= $2는 $1에 $2를 곱해 $1에 넣습니다. ^=(거듭제곱)와 %=(나머지)도 있으며, 각각 C의 Variable1=pow(Variable1, Expression1), Variable2=fmod(Variable2, Expression2)와 같습니다. |
| 문자열 잇기 | 문자열 값을 나란히 쓰면 이어집니다. $3 = $1 $2는 $1과 $2를 이은 문자열을 $3에 넣습니다. |
내장 함수
awk 언어에는 산술 함수, 문자열 함수, 일반 함수가 있습니다. 같은 프로그램에서 파일을 쓴 뒤 다시 읽으려면 close 문이 필요합니다.
산술 함수는 같은 이름의 C 언어 서브루틴과 같은 일을 합니다.
| 함수 | 돌려주는 값 |
|---|---|
atan2(y, x) |
y/x의 아크탄젠트 |
cos(x) |
x의 코사인(x는 라디안) |
sin(x) |
x의 사인(x는 라디안) |
exp(x) |
x의 지수 함수 값 |
log(x) |
x의 자연로그 |
sqrt(x) |
x의 제곱근 |
int(x) |
x를 정수로 자른 값 |
rand() |
0 이상 1 미만의 난수 n |
srand([Expr]) |
rand의 시드를 Expr로 정하고(생략하면 현재 시각), 이전 시드 값을 돌려줍니다. |
문자열 함수:
| 함수 | 설명 |
|---|---|
gsub(Ere, Repl, [In]) |
sub와 같지만 맞는 곳을 모두 바꿉니다. |
sub(Ere, Repl, [In]) |
In 문자열에서 Ere와 처음 맞는 곳을 Repl로 바꾸고, 바꾼 횟수를 돌려줍니다. Repl 안의 &(앰퍼샌드)는 Ere와 맞은 In의 문자열로 바뀝니다. In을 지정하지 않으면 레코드 전체($0)가 기본입니다. |
index(String1, String2) |
String1 안에서 String2가 나오는 위치(1부터)를 돌려줍니다. 없으면 0입니다. |
length[(String)] |
String의 길이를 문자 수로 돌려줍니다. String이 없으면 레코드 전체($0)의 길이입니다. |
blength[(String)] |
String의 길이를 바이트 수로 돌려줍니다. String이 없으면 레코드 전체($0)의 길이입니다. |
substr(String, M, [N]) |
String의 M번째 문자(첫 문자가 1)부터 N개 문자의 부분 문자열을 돌려줍니다. N이 없으면 String 끝까지입니다. |
match(String, Ere) |
String 안에서 Ere가 나오는 위치(문자 단위, 1부터)를 돌려주고, 없으면 0을 돌려줍니다. RSTART는 돌려준 값으로, RLENGTH는 맞은 문자열의 길이(없으면 -1)로 정합니다. |
split(String, A, [Ere]) |
String을 배열 원소 A[1], A[2], …, A[n]으로 나누고 n을 돌려줍니다. Ere로 나누며, Ere가 없으면 현재 필드 구분자(FS)로 나눕니다. 원소는 문자열 값으로 만들되, 문맥상 필요하면 숫자 값도 갖습니다. |
tolower(String) |
대문자를 소문자로 바꾼 문자열을 돌려줍니다. 대소문자 대응은 현재 로캘의 LC_CTYPE이 정합니다. |
toupper(String) |
소문자를 대문자로 바꾼 문자열을 돌려줍니다. 대소문자 대응은 현재 로캘의 LC_CTYPE이 정합니다. |
sprintf(Format, Expr, Expr, ...) |
Expr들을 printf 서브루틴 형식 문자열 Format에 맞춰 만든 문자열을 돌려줍니다. |
일반 함수:
| 함수 | 설명 |
|---|---|
close(Expression) |
같은 문자열 값 Expression으로 print·printf 문이나 getline 함수가 연 파일이나 파이프를 닫습니다. 잘 닫으면 0, 아니면 0이 아닌 값을 돌려줍니다. 같은 프로그램에서 파일을 쓴 뒤 다시 읽으려면 필요합니다. |
system(Command) |
Command를 실행하고 그 종료 상태를 돌려줍니다. system 서브루틴과 같습니다. |
Expression | getline [Variable] |
Expression이 지정한 명령의 출력을 파이프로 받아 레코드 하나를 읽어 Variable에 넣습니다. 그 명령 이름으로 열린 스트림이 없으면 새로 만들며, popen 서브루틴을 모드 r로 부른 것과 같습니다. 스트림이 열려 있고 Expression이 같은 문자열이면 부를 때마다 다음 레코드를 읽습니다. Variable이 없으면 $0과 NF를 정합니다. |
getline [Variable] < Expression |
Expression이 가리키는 파일에서 다음 레코드를 읽어 Variable에 넣습니다. Variable이 없으면 $0과 NF를 정합니다. |
getline [Variable] |
현재 입력 파일의 다음 레코드를 Variable에 넣습니다. Variable이 없으면 $0을 정하고 NF, NR, FNR도 정합니다. |
- 표 안의
|는 파이프 기호|입니다. - 참고:
getline은 어떤 형태든 입력에 성공하면 1, 파일 끝이면 0, 오류면 -1을 돌려줍니다.
사용자 정의 함수
사용자 정의 함수는 다음 형태로 선언합니다.
function Name (Parameter, Parameter,...) { Statements }
- 함수는 프로그램 어디서든 부를 수 있고, 정의보다 먼저 써도 됩니다. 함수의 범위는 전역입니다.
- 매개변수는 스칼라나 배열입니다. 매개변수 이름은 함수 안에서만 쓰이고, 다른 변수 이름은 모두 전역입니다. 매개변수 이름을 함수 이름이나 특수 변수와 같게 하지 말고, 전역 변수와 함수의 이름도 겹치지 않게 합니다. 같은 범위에서 스칼라와 배열의 이름이 같으면 안 됩니다.
- 정의의 매개변수 수와 부를 때 넘기는 수가 같지 않아도 됩니다. 남는 형식 매개변수는 지역 변수로 쓸 수 있습니다. 남는 스칼라 매개변수는 빈 문자열과 숫자 0으로, 남는 배열 매개변수는 빈 배열로 초기화합니다.
- 함수를 부를 때 함수 이름과 여는 괄호 사이에 공백을 두지 않습니다. 함수 호출은 중첩과 재귀가 됩니다. 중첩·재귀 호출에서 돌아오면 참조로 넘긴 배열 매개변수를 빼고 부른 함수의 매개변수 값은 그대로입니다. 값은
return문으로 돌려줍니다. - 함수 정의 안에서 여는
{앞과 닫는}뒤의 줄바꿈은 선택입니다.
함수 정의의 예입니다. 함수 average는 배열 g와 원소 수 n을 받아 평균을 구해 돌려줍니다.
function average ( g,n) {
for (i in g)
sum=sum+g[i]
avg=sum/n
return avg
}
조건문
대부분의 조건문은 C 언어의 조건문과 구문과 기능이 같습니다. 모든 조건문에서 { }로 문장을 묶을 수 있고, 식 부분과 문장 부분 사이에 줄바꿈을 넣을 수 있으며, 중괄호 안의 여러 문장은 줄바꿈이나 ;로 나눕니다.
C 언어와 같은 조건문:
| 문 | 구문과 설명 |
|---|---|
if |
if ( Expression ) { Statement } [ else Action ] |
while |
while ( Expression ) { Statement } |
for |
for ( Expression ; Expression ; Expression ) { Statement } |
break |
while이나 for 안에서 반복을 빠져나갑니다. |
continue |
while이나 for 안에서 다음 반복으로 넘어갑니다. |
C 언어 규칙을 따르지 않는 awk의 조건문:
| 문 | 구문과 설명 |
|---|---|
for...in |
for ( Variable in Array ) { Statement } — Array의 인덱스 값을 하나씩, 정해진 순서 없이 Variable에 넣으며 반복합니다. |
if...in |
if ( Variable in Array ) { Statement } — Array에 그 원소가 있으면 문장을 실행합니다. |
delete |
delete Array [ Expression ] — 배열 원소와 인덱스를 지웁니다. for (i in g) delete g[i];는 g[] 배열의 원소를 모두 지웁니다. |
exit |
exit [ Expression ] — 먼저 모든 END 동작을 순서대로 실행한 뒤, Expression을 종료 상태로 awk를 끝냅니다. END 동작 안에서 exit를 만나면 그 뒤의 END 동작은 실행하지 않습니다. |
# |
# Comment — 주석입니다. 줄의 어디서든 시작할 수 있고 줄바꿈으로 끝나야 합니다. |
next |
현재 레코드의 처리를 멈추고 다음 입력 레코드로 넘어갑니다. |
출력 문
| 문 | 구문과 설명 |
|---|---|
print |
print [ ExpressionList ] [ Redirection ] [ Expression ] — ExpressionList의 각 식 값을 표준 출력에 씁니다. 식 사이에는 OFS, 레코드 끝에는 ORS의 현재 값을 씁니다. Redirection으로 >, >>, 파이프 세 가지 재지정을 할 수 있으며, Expression은 >·>>일 때 파일 경로, 파이프일 때 명령 이름입니다. |
printf |
printf Format [, ExpressionList ] [ Redirection ] [ Expression ] — ExpressionList의 식들을 Format 형식으로 표준 출력에 씁니다. printf 명령과 똑같이 동작하되 c 변환(%c)만 다릅니다. 인수가 숫자면 그 값을 인코딩으로 하는 문자를 출력하고(0이거나 문자 집합에 없는 값이면 정의되지 않음), 숫자가 아니면 문자열의 첫 문자를 출력합니다(빈 문자열이면 정의되지 않음). |
참고: Redirection에 Expression으로 경로를 지정할 때는 문자열로 다뤄지도록 큰따옴표로 감쌉니다.
영어 원문
There are several types of action statements:
Action Statements
Built-in Functions
User-Defined Functions
Conditional Statements
Output Actions
Action Statements
Action statements are enclosed in (braces). If the statements are specified without a pattern, they are performed on every record. Multiple actions can be specified within the braces, but must be separated by new-line characters or ; (semicolons), and the statements are processed in the order they appear. Action statements include:
Arithmetical Statements The mathematical operators + (plus), - (minus), / (division), ^ (exponentiation), * (multiplication), % (modulus) are used in the form:
Expression Operator Expression
Thus, the statement:
$2 = $1 ^ 3
assigns the value of the first field raised to the third power to the second field.
Unary Statements The unary - (minus) and unary + (plus) operate as in the C programming language:
+Expression or -Expression
Increment and Decrement Statements The pre-increment and pre-decrement statements operate as in the C programming language:
++Variable or --Variable
The post-increment and post-decrement statements operate as in the C programming language:
Variable++ or Variable--
Assignment Statements The assignment operators += (addition), -= (subtraction), /= (division), and *= (multiplication) operate as in the C programming language, with the form:
Variable += Expression
Variable -= Expression
Variable /= Expression
Variable *= Expression
For example, the statement:
$1 *= $2
multiplies the field variable $1 by the field variable $2 and then assigns the new value to $1.
The assignment operators ^= (exponentiation) and %= (modulus) have the form:
Variable1^=Expression1
AND
Variable2%=Expression2
and they are equivalent to the C programming language statements:
Variable1=pow(Variable1, Expression1)
AND
Variable2=fmod(Variable2, Expression2)
where pow is the pow subroutine and fmod is the fmod subroutine.
String Concatenation Statements String values can be concatenated by stating them side by side. For example:
$3 = $1 $2
assigns the concatenation of the strings in the field variables $1 and $2 to the field variable $3.
Built-In Functions
The awk command language uses arithmetic functions, string functions, and general functions. The close Subroutine statement is necessary if you intend to write a file, then read it later in the same program.
Arithmetic Functions
The following arithmetic functions perform the same actions as the C language subroutines by the same name:
- atan2( y, x ) — Returns arctangent of y/x.
- cos( x ) — Returns cosine of x; x is in radians.
- sin( x ) — Returns sin of x; x is in radians.
- exp( x ) — Returns the exponential function of x.
- log( x ) — Returns the natural logarithm of x.
- sqrt( x ) — Returns the square root of x.
- int( x ) — Returns the value of x truncated to an integer.
- rand( ) — Returns a random number n, with 0
<=n<1. - srand( [Expr] ) — Sets the seed value for the rand function to the value of the Expr parameter, or use the time of day if the Expr parameter is omitted. The previous seed value is returned.
- String Functions
The string functions are:
- gsub( Ere, Repl, [ In ] ) — Performs exactly as the sub function, except that all occurrences of the regular expression are replaced.
- sub( Ere, Repl, [ In ] ) — Replaces the first occurrence of the extended regular expression specified by the Ere parameter in the string specified by the In parameter with the string specified by the Repl parameter. The sub function returns the number of substitutions. An & (ampersand) appearing in the string specified by the Repl parameter is replaced by the string in the In parameter that matches the extended regular expression specified by the Ere parameter. If no In parameter is specified, the default value is the entire record ( the
$0record variable). - index( String1, String2 ) — Returns the position, numbering from 1, within the string specified by the String1 parameter where the string specified by the String2 parameter occurs. If the String2 parameter does not occur in the String1 parameter, a 0 (zero) is returned.
- length [(String)] — Returns the length, in characters, of the string specified by the String parameter. If no String parameter is given, the length of the entire record (the
$0record variable) is returned. - blength [(String)] — Returns the length, in bytes, of the string specified by the String parameter. If no String parameter is given, the length of the entire record (the
$0record variable) is returned. - substr( String, M, [ N ] ) — Returns a substring with the number of characters specified by the N parameter. The substring is taken from the string specified by the String parameter, starting with the character in the position specified by the M parameter. The M parameter is specified with the first character in the String parameter as number 1. If the N parameter is not specified, the length of the substring will be from the position specified by the M parameter until the end of the String parameter.
- match( String, Ere ) — Returns the position, in characters, numbering from 1, in the string specified by the String parameter where the extended regular expression specified by the Ere parameter occurs, or else returns a 0 (zero) if the Ere parameter does not occur. The RSTART special variable is set to the return value. The RLENGTH special variable is set to the length of the matched string, or to -1 (negative one) if no match is found.
- split( String, A, [Ere] ) — Splits the string specified by the String parameter into array elements A[1], A[2], . . ., A[n], and returns the value of the n variable. The separation is done with the extended regular expression specified by the Ere parameter or with the current field separator (the FS special variable) if the Ere parameter is not given. The elements in the A array are created with string values, unless context indicates a particular element should also have a numeric value.
- tolower( String ) — Returns the string specified by the String parameter, with each uppercase character in the string changed to lowercase. The uppercase and lowercase mapping is defined by the
LC_CTYPEcategory of the current locale. - toupper( String ) — Returns the string specified by the String parameter, with each lowercase character in the string changed to uppercase. The uppercase and lowercase mapping is defined by the
LC_CTYPEcategory of the current locale. - sprintf(Format, Expr, Expr, . . . ) — Formats the expressions specified by the Expr parameters according to the printf subroutine format string specified by the Format parameter and returns the resulting string.
- General Functions
The general functions are:
- close( Expression ) — Close the file or pipe opened by a print or printf statement or a call to the getline function with the same string-valued Expression parameter. If the file or pipe is successfully closed, a 0 is returned; otherwise a non-zero value is returned. The close statement is necessary if you intend to write a file, then read the file later in the same program.
- system(Command ) — Executes the command specified by the Command parameter and returns its exit status. Equivalent to the system subroutine.
- Expression
|getline [ Variable ] — Reads a record of input from a stream piped from the output of a command specified by the Expression parameter and assigns the value of the record to the variable specified by the Variable parameter. The stream is created if no stream is currently open with the value of the Expression parameter as its command name. The stream created is equivalent to one created by a call to the popen subroutine with the Command parameter taking the value of the Expression parameter and the Mode parameter set to a value of r. Each subsequent call to the getline function reads another record, as long as the stream remains open and the Expression parameter evaluates to the same string. If a Variable parameter is not specified, the$0record variable and the NF special variable are set to the record read from the stream. - getline [ Variable ]
<Expression — Reads the next record of input from the file named by the Expression parameter and sets the variable specified by the Variable parameter to the value of the record. Each subsequent call to the getline function reads another record, as long as the stream remains open and the Expression parameter evaluates to the same string. If a Variable parameter is not specified, the$0record variable and the NF special variable are set to the record read from the stream. - getline [ Variable ] — Sets the variable specified by the Variable parameter to the next record of input from the current input file. If no Variable parameter is specified,
$0record variable is set to the value of the record, and the NF, NR, and FNR special variables are also set. - Note: All forms of the getline function return 1 for successful input, zero for end of file, and -1 for
an error.
User-Defined Functions
User-defined functions are declared in the following form: function Name (Parameter, Parameter,...) { Statements }
A function can be referred to anywhere in an awk command program, and its use can precede its definition. The scope of the function is global.
Function parameters can be either scalars or arrays. Parameter names are local to the function; all other variable names are global. The same name should not be used for different entities; for example, a parameter name should not be duplicated as a function name, or special variable. Variables with global scope should not share the name of a function. Scalars and arrays should not have the same name in the same scope.
The number of parameters in the function definition does not have to match the number of parameters used when the function is called. Excess formal parameters can be used as local variables. Extra scalar parameters are initialized with a string value equivalent to the empty string and a numeric value of 0 (zero); extra array parameters are initialized as empty arrays.
When invoking a function, no white space is placed between the function name and the opening parenthesis. Function calls can be nested and recursive. Upon return from any nested or recursive
function call, the values of all the calling function's parameters shall be unchanged, except for array parameters passed by reference. The return statement can be used to return a value.
Within a function definition, the new-line characters are optional before the opening { (brace) and after the closing } (brace).
An example of a function definition is: function average ( g,n) {
for (i in g)
sum=sum+g[i]
avg=sum/n
return avg
}
The function average is passed an array, g, and a variable, n, with the number of elements in the array. The function then obtains an average and returns it.
Conditional Statements
Most conditional statements in the awk command programming language have the same syntax and function as conditional statements in the C programming language. All of the conditional statements allow the use of (braces) to group together statements. An optional new-line can be used between the expression portion and the statement portion of the conditional statement, and new-lines or ; (semicolon) are used to separate multiple statements in (braces). Six conditional statements in C language are:
- if — Requires the following syntax: if ( Expression ) [ else Action ]
- while — Requires the following syntax: while ( Expression )
- for — Requires the following syntax: for ( Expression ; Expression ; Expression )
- break — Causes the program loop to be exited when the break statement is used in either a while or for statement.
- continue — Causes the program loop to move to the next iteration when the continue statement is used in either a while or for statement.
Five conditional statements in the awk command programming language that do not follow C-language rules are:
- for...in — Requires the following syntax: for ( Variable in Array ) The for...in statement sets the Variable parameter to each index value of the Array variable, one index at a time and in no particular order, and performs the action specified by the Statement parameter with each iteration. See the delete statement for an example of a for...in statement.
- if...in — Requires the following syntax: if ( Variable in Array ) The if...in statement searches for the existence of the Array element. The statement is performed if the Array element is found.
- delete — Requires the following syntax: delete Array [ Expression ] The delete statement deletes both the array element specified by the Array parameter and the index specified by the Expression parameter. For example, the statements:
for (i in g) delete g[i];would delete every element of theg[]array. - exit — Requires the following syntax: exit [ Expression ] The exit statement first invokes all END actions in the order they occur, then terminates the awk command with an exit status specified by the Expression parameter. No subsequent END actions are invoked if the exit statement occurs within an END action.
#— Requires the following syntax: # Comment The # statement places comments. Comments should always end with a new-line but can begin anywhere on a line.- next — Stops the processing of the current input record and proceeds with the next input record.
- Output Statements
Two output statements in the awk command programming language are:
- print — Requires the following syntax: print [ ExpressionList ] [ Redirection ] [ Expression ] The print statement writes the value of each expression specified by the ExpressionList parameter to standard output. Each expression is separated by the current value of the OFS special variable, and each record is terminated by the current value of the ORS special variable. The output can be redirected using the Redirection parameter, which can specify the three output redirections with the > (greater than), >> (double greater than), and the
|(pipe). The Redirection parameter specifies how the output is redirected, and the Expression parameter is either a path name to a file (when Redirection parameter is > or >> ) or the name of a command ( when the Redirection parameter is a|). - printf — Requires the following syntax: printf Format [, ExpressionList ] [ Redirection ] [ Expression ] The printf statement writes to standard output the expressions specified by the ExpressionList parameter in the format specified by the Format parameter. The printf statement functions exactly like the printf command, except for the
cconversion specification (%c). The Redirection and Expression parameters function the same as in the print statement. For thecconversion specification: if the argument has a numeric value, the character whose encoding is that value will be output. If the value is zero or is not the encoding of any character in the character set, the behavior is undefined. If the argument does not have a numeric value, the first character of the string value will be output; if the string does not contain any characters the behavior is undefined. - Note: If the Expression parameter specifies a path name for the Redirection parameter, the Expression
parameter should be enclosed in double quotes to insure that it is treated as a string.
변수
변수는 스칼라, 필드 변수, 배열, 특수 변수가 있습니다. 변수 이름은 숫자로 시작할 수 없습니다.
변수는 쓰기만 하면 됩니다. 함수 매개변수를 빼면 따로 선언하지 않습니다. 초기화하지 않은 스칼라 변수와 배열 원소는 숫자 값 0과 문자열 값 빈 문자열("")을 함께 갖습니다.
변수는 문맥에 따라 숫자나 문자열 값을 갖습니다. 변수마다 숫자 값, 문자열 값, 또는 둘 다를 가질 수 있습니다. 예를 들어 x = "4" + "8"은 x에 12를 넣습니다. 문자열 상수는 큰따옴표로 감쌉니다.
숫자와 문자열 사이의 명시적 변환은 없습니다. 식을 숫자로 다루게 하려면 0을 더하고, 문자열로 다루게 하려면 빈 문자열("")을 덧붙입니다.
필드 변수
필드 변수는 $(달러 기호) 뒤에 숫자나 숫자 식을 붙여 씁니다. 첫 필드는 $1, 둘째 필드는 $2, 레코드 전체는 $0입니다.
- 값을 넣으면 새 필드 변수를 만들 수 있습니다. 없는 필드, 곧 현재
$NF보다 큰 필드에 값을 넣으면 그 사이의 필드를 모두 빈 문자열로 만들고,NF를 늘리고,$0을 다시 계산합니다. - 새 필드는 현재 필드 구분자(
FS의 값)로 나뉩니다. 기본 구분자는 빈칸과 탭이며,-F플래그나 프로그램 안에서FS에 다른 값을 넣어 바꿉니다.
배열
배열은 처음에 비어 있고 크기가 동적으로 바뀝니다. 배열은 [ ](대괄호) 안에 첨자를 붙인 변수로 나타냅니다. 첨자(원소 식별자)는 숫자나 문자열이 될 수 있어 연관 배열처럼 쓸 수 있습니다. 예를 들어 다음 프로그램은 red 카운터와 green 카운터를 늘립니다.
/red/ { x["red"]++ } /green/ { y["green"]++ }
배열에는 다차원 배열처럼 첨자를 여럿 쓸 수 있습니다. awk의 배열은 실제로 1차원이라, 쉼표로 나눈 첨자들의 문자열 값을 SUBSEP 변수 값으로 이어 문자열 하나로 바꿉니다. 그래서 다음 두 인덱스는 같습니다.
x[expr1, expr2,...exprn]
x[expr1SUBSEPexpr2SUBSEP...SUBSEPexprn]
in 연산자를 쓸 때는 다차원 인덱스를 괄호로 감쌉니다. in 연산자를 빼면, 없는 배열 원소를 가리키기만 해도 그 원소가 자동으로 만들어집니다.
영어 원문
Variables can be scalars, field variables, arrays, or special variables. Variable names cannot begin with a digit.
Variables can be used just by referencing them. With the exception of function parameters, they are not explicitly declared. Uninitialized scalar variables and array elements have both a numeric value of 0 (zero) and a string value of the null string (" ").
Variables take on numeric or string values according to context. Each variable can have a numeric value, a string value, or both. For example: x = "4" + "8"
assigns the value of 12 to the variable x. For string constants, expressions should be enclosed in " " (double quotation) marks.
There are no explicit conversions between numbers and strings. To force an expression to be treated as a number, add 0 (zero) to it. To force an expression to be treated as a string, append a null string (" ").
Field Variables
Field variables are designated by a $ (dollar sign) followed by a number or numerical expression. The first field in a record is assigned the $1 variable , the second field is assigned to the $2 variable, and so forth. The $0 field variable is assigned to the entire record. New field variables can be created by assigning a value to them. Assigning a value to a non-existent field, that is, any field larger than the current value of $NF field variable, forces the creation of any intervening fields (set to the null string), increases the value of the NF special variable, and forces the value of $0 record variable to be recalculated. The new fields are separated by the current field separator ( which is the value of the FS special variable). Blanks and tabs are the default field separators. To change the field separator, use the -F flag, or assign the FS special variable a different value in the awk command program.
Arrays
Arrays are initially empty and their sizes change dynamically. Arrays are represented by a variable with subscripts in [ ] (square brackets). The subscripts, or element identifiers, can be numbers of strings, which provide a type of associative array capability. For example, the program: /red/ { x["red"]++ } /green/ { y["green"]++ }
increments counts for both the red counter and the green counter.
Arrays can be indexed with more than one subscript, similar to multidimensional arrays in some programming languages. Because programming arrays for the awk command are really one dimensional, the comma-separated subscripts are converted to a single string by concatenating the string values of the separate expressions, with each expression separated by the value of the SUBSEP environmental variable. Therefore, the following two index operations are equivalent: x[expr1, expr2,...exprn]
AND x[expr1SUBSEPexpr2SUBSEP...SUBSEPexprn]
When using the in operator, a multidimensional Index value should be contained within parentheses. Except for the in operator, any reference to a nonexistent array element automatically creates that element.
특수 변수
다음 변수는 awk에서 특별한 뜻이 있습니다.
| 변수 | 뜻 |
|---|---|
ARGC |
ARGV 배열의 원소 수입니다. 바꿀 수 있습니다. |
ARGV |
명령줄의 File 변수나 Assignment 변수를 순서대로 하나씩 담은 배열로, 0부터 ARGC-1까지 번호가 붙습니다. 입력 파일 하나를 마칠 때마다 다음 원소가 다음 입력 파일의 이름이 됩니다. 다만 다음 원소가 대입문이면 대입을 평가하고, 빈 값이면 건너뛰고(그래서 원소를 빈 값으로 바꿔 입력 파일을 건너뛸 수 있음), ARGV[ARGC-1]이면 입력 파일의 끝으로 해석합니다. |
CONVFMT |
숫자를 문자열로 바꿀 때 쓰는 printf 형식입니다(출력 문에서는 OFMT를 씀). 기본은 "%.6g"입니다. |
ENVIRON |
awk가 동작하는 환경을 나타내는 배열입니다. 원소는 ENVIRON["환경변수이름"] = 값 형태입니다. 값은 awk를 시작할 때 정해지며, ENVIRON을 바꿔도 실행이 끝날 때까지 그 환경을 씁니다. |
FILENAME |
현재 입력 파일의 경로입니다. BEGIN 동작 중에는 정의되지 않고, END 동작 중에는 마지막으로 처리한 입력 파일의 이름입니다. |
FNR |
현재 파일 안에서 현재 입력 레코드의 번호입니다. |
FS |
입력 필드 구분자입니다. 기본은 공백이며, 공백이면 로캘이 정의한 공백 여러 개로 필드를 나눌 수 있습니다. 문자 하나로 정하면 그 문자가 나올 때마다 나누고, 확장 정규 표현식으로 정하면 그 식과 맞는 부분마다 나눕니다. |
NF |
현재 레코드의 필드 수이며, 최대 99입니다. BEGIN 동작 안에서는 그 전에 Variable 없는 getline을 부르지 않았으면 정의되지 않습니다. END 동작 안에서는 마지막 레코드의 값을 유지합니다(그 전에 재지정한 Variable 없는 getline을 부르지 않았다면). |
NR |
현재 입력 레코드의 번호입니다. BEGIN 안에서는 0, END 안에서는 마지막으로 처리한 레코드의 번호입니다. |
OFMT |
출력 문에서 숫자를 문자열로 바꿀 때 쓰는 printf 형식입니다. 기본은 "%.6g"입니다. |
OFS |
출력 필드 구분자입니다(기본은 빈칸). |
ORS |
출력 레코드 구분자입니다(기본은 줄바꿈). |
RLENGTH |
match 함수와 맞은 문자열의 길이입니다. |
RS |
입력 레코드 구분자입니다(기본은 줄바꿈). RS가 빈 값이면 빈 줄 하나 이상으로 레코드를 나누고, 입력의 처음과 끝의 빈 줄은 빈 레코드를 만들지 않으며, FS 값과 상관없이 줄바꿈 문자가 늘 필드 구분자가 됩니다. |
RSTART |
match 함수와 맞은 문자열의 시작 위치(1부터)입니다. match의 반환값과 같습니다. |
SUBSEP |
여러 첨자를 나누는 구분자입니다. 기본은 \031입니다. |
영어 원문
The following variables have special meaning for the awk command:
- ARGC — The number of elements in the ARGV array. This value can be altered.
- ARGV — The array with each member containing one of the File variables or Assignment variables, taken in order from the command line, and numbered from 0 (zero) to ARGC -1. As each input file is finished, the next member of the ARGV array provides the name of the next input file, unless: • The next member is an Assignment statement, in which case the assignment is evaluated. • The next member has a null value, in which case the member is skipped. Programs can skip selected input files by setting the member of the ARGV array that contains that input file to a null value. • The next member is the current value of ARGV [ARGC -1], which the awk command interprets as the end of the input files.
- CONVFMT — The printf format for converting numbers to strings (except for output statements, where the OFMT special variable is used). The default is "%.6g".
- ENVIRON — An array representing the environment under which the awk command operates. Each element of the array is of the form: ENVIRON [ "Environment VariableName" ] = EnvironmentVariableValue The values are set when the awk command begins execution, and that environment is used until the end of execution, regardless of any modification of the ENVIRON special variable.
- FILENAME — The path name of the current input file. During the execution of a BEGIN action, the value of FILENAME is undefined. During the execution of an END action, the value is the name of the last input file processed.
- FNR — The number of the current input record in the current file.
- FS — The input field separator. The default value is a blank. If the input field separator is a blank, any number of locale-defined spaces can separate fields. The FS special variable can take two additional values: • With FS set to a single character, fields are separated by each single occurrence of the character. • With FS set to an extended regular expression, each occurrence of a sequence matching the extended regular expression separates fields.
- NF — The number of fields in the current record, with a limit of 99. Inside a BEGIN action, the NF special variable is undefined unless a getline function without a Variable parameter has been issued previously. Inside an END action, the NF special variable retains the value it had for the last record read, unless a subsequent, redirected, getline function without a Variable parameter is issued prior to entering the END action.
- NR — The number of the current input record. Inside a BEGIN action the value of the NR special variable is 0 (zero). Inside an END action, the value is the number of the last record processed.
- OFMT — The printf format for converting numbers to strings in output statements. The default is "% .6g".
- OFS — The output field separator (default is a space).
- ORS — The output record separator (default is a new-line character).
- RLENGTH — The length of the string matched by the match function.
- RS — Input record separator (default is a new-line character). If the RS special variable is null, records are separated by sequences of one or more blank lines; leading or trailing blank lines do not result in empty records at the beginning or end of input; and the new-line character is always a field separator, regardless of the value of the FS special variable.
- RSTART — The starting position of the string matched by the match function, numbering from 1. Equivalent to the return value of the match function.
- SUBSEP — Separates multiple subscripts. The default is
\031.
플래그
| 플래그 | 설명 |
|---|---|
-f ProgramFile |
ProgramFile 파일에서 awk의 명령을 가져옵니다. -f를 여러 번 지정하면 지정한 순서대로 이은 파일들을 명령으로 씁니다. |
-u |
출력을 버퍼에 모으지 않고 바로 표시합니다. 기본은 버퍼에 모아 출력합니다. 6.1부터 |
-F Ere |
확장 정규 표현식 Ere를 필드 구분자로 씁니다. 기본 필드 구분자는 공백입니다. |
-v Assignment |
awk 프로그램의 변수에 값을 넣습니다. 형태는 Name=Value입니다. Name은 밑줄, 숫자, 영문자로 이뤄지며 영문자나 밑줄로 시작해야 합니다. Value도 밑줄, 숫자, 영문자로 이뤄지며 앞뒤에 큰따옴표가 있는 것처럼(문자열 값처럼) 다룹니다. Value가 숫자면 숫자 값도 넣습니다. -v 대입은 BEGIN 부분을 포함해 프로그램의 어느 부분보다도 먼저 일어납니다. |
| Assignment | awk 프로그램의 변수에 값을 넣습니다. -v의 Assignment와 형태와 기능이 같고 처리 시점만 다릅니다. 명령줄에서 바로 뒤에 오는 입력 파일(File 변수)을 처리하기 직전에 처리합니다. 여러 입력 파일 중 첫 파일 바로 앞에 있으면 BEGIN 부분 바로 뒤에, 마지막 파일 뒤에 있으면 END 부분 전에 처리합니다. 입력 파일이 없으면 표준 입력을 읽기 전에 처리합니다. |
| File | 처리할 입력이 든 파일의 이름입니다. File이 없거나 -(빼기)를 지정하면 표준 입력을 처리합니다. |
'Program' |
awk의 명령을 담습니다. -f가 없으면 명령줄의 첫 항목이어야 하며, 작은따옴표로 감쌉니다. |
영어 원문
-fProgramFile — Obtains instructions for the awk command from the file specified by the ProgramFile variable. If the-fflag is specified multiple times, the concatenation of the files, in the order specified, will be used as the set of instructions.-u— Displays the output in an unbuffered mode. If this flag is used, the awk command does not buffer the output. Instead, it displays the output instantaneously. By default, the awk command displays the output in a buffered mode.-FEre — Uses the extended regular expression specified by the Ere variable as the field separator. The default field separator is a blank.-vAssignment — Assigns a value to a variable for the awk command's programming language. The Assignment parameter is in the form of Name = Value. The Name portion specifies the name of the variable and can be any combination of underscores, digits, and alphabetic characters, but it must start with either an alphabetic character or an underscore. The Value portion is also composed of underscores, digits, and alphabetic characters, and is treated as if it were preceded and followed by a " (double-quotation character, similar to a string value). If the Value portion is numeric, the variable will also be assigned the numeric value. The assignment specified by the-vflag occurs before any portion of the awk command's program is executed, including the BEGIN section.- Assignment — Assigns a value to a variable for the awk command's programming language. It has the same form and function as the Assignment variable with the
-vflag, except for the time each is processed. The Assignment parameter is processed just prior to the input file (specified by the File variable) that follows it on the command line. If the Assignment parameter is specified just prior to the first of multiple input files, the assignments are processed just after the BEGIN sections (if any). If an Assignment parameter occurs after the last file, the assignment is processed before the END sections (if any). If no input files are specified, the assignments are processed the standard input is read. - File — Specifies the name of the file that contains the input for processing. If no File variable is specified, or if a
-(minus) sign is specified, standard input is processed. - 'Program' — Contains the instructions for the awk command. If the
-fflag is not specified, the Program variable should be the first item on the command line. It should be bracketed by ' ' (single quotes).
종료 상태
| 값 | 뜻 |
|---|---|
| 0 | 잘 끝났습니다. |
| 0보다 큼 | 오류가 났습니다. |
프로그램 안에서 exit [ Expression ] 조건문으로 종료 상태를 바꿀 수 있습니다.
영어 원문
This command returns the following exit values:
- 0 — Successful completion.
>0— An error occurred.
You can alter the exit status within the program by using the exit [ Expression ] conditional statement.
예제
- 72자보다 긴 줄을 표시합니다. 동작을 지정하지 않았으므로
chapter1에서 72자보다 긴 줄을 골라 표준 출력에 씁니다. 탭 문자는 1바이트로 셉니다.
awk 'length >72' chapter1
start와stop두 단어 사이의 줄을start와stop이 든 줄까지 포함해 모두 표시합니다.
awk '/start/,/stop/' chapter1
awk프로그램sum2.awk로chapter1파일을 처리합니다.
awk -f sum2.awk chapter1
sum2.awk는 입력 파일 둘째 열의 합과 평균을 구합니다.
{
sum += $2
}
END {
print "Sum: ", sum;
print "Average:", sum/NR;
}
첫 동작은 줄마다 둘째 필드 값을 변수 sum에 더합니다. 모든 변수는 처음 쓸 때 숫자 0으로 초기화됩니다. 둘째 동작 앞의 END 패턴 때문에 그 동작은 입력 파일을 모두 읽은 뒤에 합니다. 평균을 구할 때 쓰는 NR은 지금까지 읽은 레코드 수입니다.
- 앞의 두 필드를 순서를 바꿔 출력합니다.
awk '{ print $2, $1 }' chapter1
- 다음 프로그램은 쉼표나 빈칸·탭으로 나뉜
chapter2의 앞 두 필드를 출력하고, 첫 열을 더해 합과 평균을 출력합니다.
awk -f sum3.awk chapter2
sum3.awk의 내용:
BEGIN {FS = ",|[ \t]+"}
{print $1, $2}
{s += $1}
END {print "sum is",s,"average is", s/NR }
관련 명령어: bc, egrep, grep, lex, sed
영어 원문
- To display the lines of a file that are longer than 72 characters, enter:
awk ’length >72’ chapter1
This selects each line of the chapter1 file that is longer than 72 characters and writes these lines to standard output, because no Action is specified. A tab character is counted as 1 byte.
To display all lines between the words
startandstop,including"start"and"stop",enter:awk ’/start/,/stop/’ chapter1To run an awk command program,
sum2.awk,that processes the file,chapter1, enter:awk -f sum2.awk chapter1
The following program, sum2.awk, computes the sum and average of the numbers in the second column of the input file, chapter1:
{
sum += $2
}
END {
print "Sum: ", sum;
print "Average:", sum/NR;
}
The first action adds the value of the second field of each line to the variable sum. All variables are initialized to the numeric value of 0 (zero) when first referenced. The pattern END before the second
action causes those actions to be performed after all of the input file has been read. The NR special variable, which is used to calculate the average, is a special variable specifying the number of records that have been read.
- To print the first two fields in opposite order, enter:
awk ’{ print $2, $1 }’ chapter1
- The following awk program
awk -f sum3.awk chapter2
prints the first two fields of the file chapter2 with input fields separated by comma and/or blanks and tabs, and then adds up the first column, and prints the sum and average:
BEGIN {FS = ",|[ \t]+"}
{print $1, $2}
{s += $1}
END {print "sum is",s,"average is", s/NR }
Related reference:
- bc Command
Related information:
- egrep command
- grep command
- lex command
- sed command
리눅스(GNU)와 다른 점
| 항목 | AIX 5.3·6.1 awk | GNU awk(gawk) |
|---|---|---|
blength |
바이트 길이 함수가 있음 | 없음 |
NF의 한도 |
99개 | 사실상 제한 없음 |
-u |
버퍼 없는 출력(6.1) | 없음(fflush()를 씀) |
| 확장 | POSIX awk 범위 | gensub, strftime, systime, --re-interval, -i inplace 같은 확장이 있음 |
리눅스에서 쓰던 gawk 스크립트를 AIX로 옮길 때는 strftime, gensub, length(배열) 같은 gawk 확장을 쓰지 않았는지 확인합니다.