gawkのヘルプ・マニュアル
日本語 英語
gawk --help
使い方: gawk [POSIX または GNU 形式オプション] -f プログラムファイル [--] 入力ファイル …
使い方: gawk [POSIX または GNU 形式オプション] [--] 'プログラム' 入力ファイル …
POSIX オプション: GNU 長形式オプション
-f プログラムファイル --file=プログラムファイル
-F フィールドセパレータ --field-separator=フィールドセパレータ
-v 変数=代入値 --assign=変数=代入値
-m[fr] 数値
-O --optimize
-W compat --compat
-W copyleft --copyleft
-W copyright --copyright
-W dump-variables[=ファイル] --dump-variables[=ファイル]
-W exec=ファイル --exec=ファイル
-W gen-po --gen-po
-W help --help
-W lint[=fatal] --lint[=fatal]
-W lint-old --lint-old
-W non-decimal-data --non-decimal-data
-W profile[=ファイル] --profile[=ファイル]
-W posix --posix
-W re-interval --re-interval
-W source=プログラム文 --source=プログラム文
-W traditional --traditional
-W usage --usage
-W use-lc-numeric --use-lc-numeric
-W version --version
バグを報告するには、`gawk.info(英文)' の `Bugs' ノードを
参照してください。 印刷されたマニュアルで対応するセクション
は、`Reporting Problems and Bugs' です。
gawk は、パターンを検索、そして処理する言語です。
デフォルト設定では、標準入力を読み込み、標準出力に書き出します。
使用例:
gawk '{ sum += $1 }; END { print sum }' 入力ファイル
gawk -F: '{ print $1 }' /etc/passwd
Usage: gawk [POSIX or GNU style options] -f progfile [--] file ...
Usage: gawk [POSIX or GNU style options] [--] 'program' file ...
POSIX options: GNU long options:
-f progfile --file=progfile
-F fs --field-separator=fs
-v var=val --assign=var=val
-m[fr] val
-O --optimize
-W compat --compat
-W copyleft --copyleft
-W copyright --copyright
-W dump-variables[=file] --dump-variables[=file]
-W exec=file --exec=file
-W gen-po --gen-po
-W help --help
-W lint[=fatal] --lint[=fatal]
-W lint-old --lint-old
-W non-decimal-data --non-decimal-data
-W profile[=file] --profile[=file]
-W posix --posix
-W re-interval --re-interval
-W source=program-text --source=program-text
-W traditional --traditional
-W usage --usage
-W use-lc-numeric --use-lc-numeric
-W version --version
To report bugs, see node `Bugs' in `gawk.info', which is
section `Reporting Problems and Bugs' in the printed version.
gawk is a pattern scanning and processing language.
By default it reads standard input and writes standard output.
Examples:
gawk '{ sum += $1 }; END { print sum }' file
gawk -F: '{ print $1 }' /etc/passwd
man gawk
GAWK(1) Utility Commands GAWK(1)
名称
gawk - パターン検索・処理言語
書式
awk [ POSIX or GNU style options ] -f program-file [ -- ] file ...
gawk [ POSIX or GNU style options ] [ -- ] program-text file ...
解説
gawk は GNU プロジェクトが実装した プログラミング言語 AWK の処理系です
。本処理系は POSIX 1003.2 コマンド言語とユーティリティ規約に定められ た
言 語 の定義に適合しています。本バージョンはまた、Aho, Kernighan, Wein-
berger の著書 The AWK Programming Language の記述にもとづい て お り 、
System V Release 4 UNIX の awk の付加機能も含んでいます。 gawk はまた
、Bell Labs の新機能および GNU 独自の拡張も提供します。
コマンドラインは、 gawk へのオプション、(もし -f または --file オプショ
ンにより指定されていなければ)AWK のプログラムテキスト、そして残りの引数
列からなります。この残りの引数列は、定義済み AWK 変数 ARGC, ARGV を用い
ることで参照できます。
オプションフォーマット
gawk へのオプションは、伝統的な POSIX 形式の 1 文字オプションと、GNU 形
式のロングオプションがあります。 POSIX 形式のオプションは単一の “-” で
始まり、一方 GNU 形式のものは “--” で始まります。ロングオプションは GNU
の独自仕様と POSIX の必須仕様の両方について用意されています。
POSIX 標準に従い、 gawk 独自仕様のオプションは -W オプションへの引数 で
与 えます。複数の -W オプションを指定することもできます。後述のように、
各 -W オプションには、それに対応するロングオプションが存在します。ロ ン
グオプションへの引数は、空白を入れずに = でつないで指定するか、その次の
コマンドライン引数として渡すことができます。ロングオプションは、短縮 形
が一意である限り、短縮することができます。
オプション
gawk は以下のオプションを受け付けます。
-F fs
--field-separator fs
入力フィールドセパレータ (変数 FS の値)を fs とします。
-v var=val
--assign var=val
プログラムを実行する前に、変数 var に値 val を設定します。このよ
うにして設定した変数は、 AWK プログラムの BEGIN ブロック内でも参
照できます。
-f program-file
--file program-file
awk への第 1 引数を用いるかわりに、AWK プログラムをファイル pro-
gram-file から読み込みます。 -f (または --file ) オプションは 複
数回使用することができます。
-mf NNN
-mr NNN
さまざまなメモリの制限値を NNN に設定します。フラグ f は最大フィ
ールド数、フラグ r は最大レコードサイズを設定します。この 2 つの
フラグと -m オプションは、Bell Labs バージョンの UNIX awk に由来
しています。しかし、 gawk にはこのような制限はありませんの で 、
gawk では本オプションは無視されます。
-W traditional
-W compat
--traditional
--compat
互換モードで動作します。互換モードでは、 gawk は UNIX awk と等価
な動作を行い、GNU 独自拡張は解釈できません。このオプションの他の
形 式よりも、 --traditional を使用することが好まれます。詳しくは
後述の GNU 拡張を参照してください。
-W copyleft
-W copyright
--copyleft
--copyright
GNU の著作権表示の短いバージョンを標準出力へ書き出し、成功状態で
終了します。
-W help
-W usage
--help
--usage
短 めのオプション一覧を標準出力へ書き出します。 ( GNU コーディン
グ規約に従い、本オプションを指定すると awk はただちに終了し、 成
功を意味する終了ステータスを返します。)
-W lint
--lint 他の AWK での処理が疑わしい、あるいは他の AWK との互換性がない構
造がある場合に警告を行います。
-W lint-old
--lint-old
オリジナルの Unix awk へ移植できない構造に関して警告を行います。
-W posix
--posix
互換モードをオンにし、更に以下の制約が課せられます。
· \x エスケープシーケンスを解釈しません。
· FS が単一の空白に設定された場合、空白とタブのみがフィールドを
区切り、改行はフィールドを区切りません。
· キーワード function に対応する別名 func を解釈しません。
· 演算子 ^ や ^= のかわりに ** や **= を用いることができません。
· fflush() 関数は利用できません。
-W re-interval
--re-interval
正 規 表現のマッチングで インターバル表現 (interval expressions)
を有効にします (後述の 正規表現を参照してください)。インターバル
表 現 は伝統的な AWK 言語では利用できませんでした。 awk と egrep
が一貫性を持つように、POSIX 標準がこれらを追加しました。しかし、
こ れらを使用すると古い AWK プログラムを動かなくしてしまうでしょ
うから、このオプションによって要求されたときと、 --posix が指 定
されたときに、 gawk はこれらの機能を提供します。
-W source program-text
--source program-text
program-text を AWK プログラムとして用います。本オプションにより
、ライブラリ化された関数 ( -f または --file オプションを用いて読
み込む) とコマンドラインから入力されたプログラムを簡単に合成する
ことができます。これは、主にシェルスクリプトで用いられる中規模か
ら大規模な AWK プログラムのために用意されました。
-W version
--version
実行された gawk プログラムのバージョン情報を標準出力へ書き出しま
す。これは主に、あなたが使用している gawk プロ グ ラ ム が Free
Software Foundation が配布しているプログラムのうち、最新のもので
あるかどうかを知る場合に便利です。またバグレポートのときにも有用
で す。 (本オプションを指定すると、 GNU コーディング規約に従い、
awk はただちに終了し、成功を意味する終了ステータスを返します。)
-- オプションの終了を意味します。AWK プログラムに “-” から始まる オ
プ シ ョ ン ではない引数を与える場合に便利です。これは、主に他の
POSIX プログラムの多くが引数に対して行う解釈と一貫性を保つために
あります。
互 換モードでは、他のオプションは不正であるとされるか、無視されます。通
常の実行において、プログラムテキストがコマンドラインに指定されていれ ば
、 不明なオプションは、AWK プログラムに ARGV 配列を通して渡されます。こ
れは、AWK プログラムを “#!” 機構を用いて実行する場合に特に便利です。
AWK プログラムの実行
AWK プログラムは、パターンとアクションの組の列と、(もし必要なら) 関数定
義からなります。
pattern { action statements }
function name(parameter list) { statements }
gawk は ま ず 、 program-file (複数可) が指定されていればそれから、
--source の引数から、あるいは、最初のオプションではない引数からプログラ
ム を読み込みます。 -f と --source オプションは、コマンドラインで複数回
指定できます。 gawk は、すべての program-file とコマンドラインで指定 し
たプログラムを結合して使用します。新しく作った AWK プログラムひとつひと
つに AWK 関数のライブラリを埋め込む必要が無いので、この機能はライブラリ
の 構築に便利です。また、ライブラリ関数とコマンドラインで指定したプログ
ラムとを混合して使うことも可能にしています。
環境変数 AWKPATH により、 -f オプションで指定されたファイルを検索するパ
ス を 指 定 できます。 AWKPATH が設定されていない場合のデフォルトパスは
".:/usr/local/share/awk" です。 (実際のディレクトリは gawk がどのように
構 築/インストールされたかに依存して、さまざまなものとなります。) -f オ
プションで指定したファイル名が “/” を含んでいる場合は、パス検索は行われ
ません。
gawk は、 AWK プログラムを次の順序で実行します。まず、 -v オプションで
指定された変数への代入をすべて行います。次に、プログラムを内部形式に コ
ンパイルします。そして、(もし存在すれば) BEGIN ブロック (複数存在可) を
実行します。配列 ARGV で指定されたファイルを順に読み、処理を行います (
コ マンドラインでファイル名が指定されていなければ、標準入力に対して処理
を行います)。
コマンドラインで指定されたファイル名が var=val という形式ならば、それは
変 数への代入であると解釈されます。変数 var は値 val に設定されます (こ
れは、すべての BEGIN ブロックを実行したあとに行われます)。コマンドラ イ
ン での変数の代入は、AWK が入力をフィールドやレコードに分割するためのセ
パレータを実行時に変更するのに便利です。また、1 つのデータファイルに 対
し数回処理を行う必要がある場合、状態をコントロールするのにも便利です。
配列 ARGV の要素に空 ("") がある場合、 gawk はその要素を無視します。
gawk は、入力された各レコードに対してマッチする パターンが AWK プログラ
ム内にあるかどうかを検索します。そのレコードにマッチしたパターンすべ て
について、それぞれ対応する アクションが実行されます。パターンは、プログ
ラムテキストに出現した順序で検索されます。
入力が尽きると、 gawk は (もしあれば) END ブロック (複数存在可) を実 行
します。
変数、レコード、フィールド
AWK における変数は動的、すなわち、最初に使用されたときに生成されます。
変数の値は、浮動小数点数か、文字列か、あるいは両方です。変数の用いら れ
方 により変化します。AWK ではまた、1 次元配列を利用することができます。
多次元配列も、擬似的にではありますが、利用可能です。プログラム実行開 始
時 に、いくつかの定義済み変数が設定されます。これらを必要に応じて説明し
、以下でまとめます。
レコード
通常、レコードは改行文字により区切られます。レコードの区切りは、組み 込
み 変数 RS へ値を代入することにより、制御できます。 RS が単一文字の場合
、その文字がレコードを区切ります。そうでない場合は、 RS は正規表現と な
り ます。入力中のテキストで、この正規表現にマッチするものがレコードを区
切ります。しかし互換モードでは、文字列値の最初の文字だけが、レコード セ
パ レータに使用されます。 RS が空文字列に設定されているときには、レコー
ドは空行で区切られます。 RS が空文字列に設定されたときには、 FS の値 に
かかわらず、改行文字は常にフィールドセパレータとなります。
フィールド
入力レコードを読み込むごとに、 gawk はそのレコードを フィールドに分割し
ます。分割する際には、変数 FS の値がフィールドセパレータとして参照さ れ
ま す。 FS の値が1文字なら、その文字を境にフィールドが分割されます。 FS
が空文字列の場合、個々の文字がフィールドセパレータとなります。いずれ で
も ない場合、 FS は完全な正規表現であると解釈されます。特殊な場合として
FS が単一の空白のときには、フィールドは連続した空白・タブ・改行により分
割されます。 (後述の --posix の議論を参照してください)。変数 IGNORECASE
(下記参照) の値は、 FS が正規表現の場合フィールド分割にも影響を与えるこ
と と、 RS が正規表現の場合レコード分割にも影響を与えることに注意してく
ださい。
変数 FIELDWIDTHS の値が空白で区切られた数字の列である場合、各フィールド
は 固定長であると解釈され、 gawk は指定された幅ごとにフィールドの分割を
行います。この場合、 FS の値は無視されます。 FS に新たに値を設定する こ
とにより、この FIELDWIDTHS の効果を打ち消し、標準の動作に戻すことができ
ます。
入力レコード中の各フィールドの値は、左から $1, $2 等という名前で参照 で
き ます。 $0 はレコード全体です。フィールドに値を代入することもできます
。フィールドは定数だけでなく、変数によって参照することもできます。以 下
の例では、入力レコードの 5 番目のフィールドの値を出力します。
n = 5
print $n
変数 NF は、自動的に入力レコードのフィールドの数に設定されます。
存在しないフィールド (すなわち、 $NF より右のフィールド) を参照した結果
は空文字列になります。しかしながら、存在しないフィールドへの代入(たとえ
ば、 $(NF+2)=5 ) は NF の値を増加させ、間のフィールドには空文字が設定さ
れます。さらに $0 の値は、フィールドの値を変数 OFS の値でフィールドを区
切 ったものとして再計算されます。負のフィールド番号への参照は致命的エラ
ーとなります。 NF を減少させると、新しい値を越えるフィールドの値は失 わ
れます。 $0 の値は、フィールドの値を変数 OFS の値でフィールドを区切った
ものとして再計算されます。
組み込み変数
gawk の組み込み変数は以下のとおりです。
ARGC コマンドライン引数の個数 ( gawk へのオプションと、プログ ラ
ム指定は含みません)。
ARGIND 現在処理中のファイル名が格納されている配列 ARGV のインデッ
クス。
ARGV コマンドライン引数の配列。配列は、 0 から ARGC - 1 までのイ
ン デックスを持ちます。 ARGV の内容を変更することで、入力に
用いるファイル名を変更することができます。
CONVFMT 数値の変換フォーマット。デフォルト値は "%.6g" です。
ENVIRON 現在の環境変数の値からなる配列。配列は、環境変数名により イ
ン デ ッ クスされ、各要素の値はその環境変数の値です (例えば
ENVIRON["HOME"] は /home/arnold となるでしょう)。本配列に代
入 を行っても、 gawk からリダイレクトや system() 関数により
実行されるプログラムの環境には影響を与えません(これは、将来
の gawk では変更される可能性があります)。
ERRNO getline のリダイレクト、 getline による読み込み、 close()
関数の実行時のいずれかにシステムエラーが発生した場合、変 数
ERRNO にはエラーの内容を示した文字列が設定されます。
FIELDWIDTHS 空白で区切られたフィールド長のリスト。もしこの値が設定され
ていれば、 gawk は FS の値を用いてフィールド分割するかわ り
に 、固定長のフィールド分割を行います。固定長のフィールド分
割機能はまだ実験的なもので、 gawk が改良されるに従って意 味
が変化する可能性があります。
FILENAME 現在の入力ファイル名。もし、コマンドラインで入力ファイルが
指定されていなければ、 FILENAME の値は “-” です。しかしなが
ら、 BEGIN ブロック内では FILENAME は未定義です。
FNR 現在の入力ファイルにおける入力レコード番号。
FS 入力フィールドセパレータ。デフォルトでは単一の空白です。上
述の フィールドを参照してください。
IGNORECASE すべての正規表現と文字列操作において大文字小文字の区別を 制
御します。もし、 IGNORECASE が 0 でない値に設定されていれば
、文字列比較、ルールのパターンマッチ、 FS によるフィール ド
分割、 RS によるレコード分割、 ~ と !~ による正規表現マッチ
、定義済み関数 gensub(), gsub(), index(), match(), split(),
sub() において大文字と小文字の違いは無視されます。このため
、 IGNORECASE が 0 以外の値なら、 /aB/ は "ab", "aB", "Ab",
"AB" のいずれにもマッチすることになります。他のAWK 変数と同
様に IGNORECASE の初期値は 0 なので、通常は正規表現と文字列
操 作において大文字と小文字は区別されます。 Unix では、大文
字小文字を無視する場合、 ISO 8859-1 Latin-1 文字集合全て を
使用できます。 注: 3.0 以前の gawk では IGNORECASE は正規表
現操作のみに影響しました。現在は文字列比較にも影響します。
NF 現在の入力レコードのフィールド数。
NR 現在までに読み込んだ入力レコード数の合計。
OFMT 数字の出力フォーマット。デフォルト値は "%.6g" です。
OFS 出力フィールドセパレータ。デフォルトは空白です。
ORS 出力レコードセパレータ。デフォルトは改行です。
RS 入力レコードセパレータ。デフォルトは改行です。
RT レコードターミネータ。 gawk は、 RS で指定される文字また は
正規表現にマッチする入力テキストを、 RT に設定します。
RSTART match() によりマッチした最初の文字の位置。0 はマッチしなか
ったことを示します。
RLENGTH match() によりマッチした文字列の長さ。-1 はマッチしなかった
ことを示します。
SUBSEP 多次元配列を実現する際に用いられる、配列のインデックスを結
合する文字。デフォルト値は "\034" です。
配列
配列は、ブラケット ([ と ]) の間の式によってインデックスを指定します 。
もし式が式のリスト(式, 式 ...) なら、式の値を変数 SUBSEP の値を区切りと
して結合した文字列をインデックスとして用います。これにより、多次元配 列
をシミュレートしています。例えば、
i = "A"; j = "B"; k = "C"
x[i, j, k] = "hello, world\n"
は、文字列 "hello, world\n" を、文字列 "A\034B\034C" でインデックスした
配列 x の要素に代入しています。 AWK の配列はすべて、文字列によりイン デ
ックスを行う連想配列です。
特殊な演算子 in を if または while ステートメントで用いることによって、
あるインデックス値における配列の値が定義されているかを調べることがで き
ます。
if (val in array)
print array[val]
もし、配列が多次元インデックスを持つなら、 (i, j) in array を用います。
in はまた、 for ループ中で、配列のすべてのインデックス値について繰り 返
すために用いることができます。
配 列 の 要素は、 delete ステートメントを用いて削除することができます。
delete ステートメントはまた、添字を指定せずに配列名のみを指定することに
より、配列全体を削除するためにも使えます。
変数の型と変換
変数とフィールドは、(浮動小数点数の) 数値または文字列、あるいは両方とし
て扱われます。変数の値がどのように解釈されるかは、変数の使われ方によ っ
て 変化します。数式中で用いられれば変数は数値として解釈され、文字列とし
て用いられれば文字列として解釈されます。
変数の値を強制的に数値であると解釈させたい場合は、変数に 0 を加えます。
文字列と解釈させたい場合は空文字列を結合します。
文字列を数値に変換する必要がある場合、変換は atof(3) によって行われます
。数値を文字列に変換する場合は、変数 CONVFMT の値をフォーマット文字列と
し て用いて、 sprintf(3) により行われます。AWK ではすべての数値は浮動小
数点数ですが、整数値は常に整数として変換が行われます。よって、以下の 場
合、
CONVFMT = "%2.2f"
a = 12
b = a ""
変数 b は文字列値 "12" となり、"12.00" とはなりません。
gawk は、以下のようにして比較を行います: 2 つの変数が数値なら数値として
比較します。もし片方が数値で片方が‘数値’文字列なら、数値として比較さ れ
ま す。片方が数値でない文字列なら、数値のほうが文字列に変換され、文字列
として比較されます。両方とも文字列なら、文字列として比較されます。POSIX
標 準に従うなら、両方とも数値文字列の場合は数値として比較しますが、これ
は明らかに間違いです。 gawk はそのような動作をしません。
"57" のような文字列定数は数値文字列では なく、文字列定数です。「数値 文
字列」の概念は、フィールド、 getline の入力、 FILENAME 、 ARGV の要素、
ENVIRON の要素、数値文字列から split() によって作成された配列の要素に対
してのみ適用されます。基本的な考え方では、 ユーザ入力、それも数値に見え
るユーザ入力のみが数値として扱われます。
初期化されていない変数は、数値としては 0 を、文字列としては "" (空文 字
列) を持ちます。
パターンとアクション
awk は行指向の言語です。まずパターン、次にアクションが続きます。アクシ
ョンは { と } で囲みます。パターンまたはアクションは省略することもで き
ま す。もちろん、両方とも省略してしまっては意味がありません。パターンが
ない場合、アクションはすべての入力レコードに対して適用されます。省略 さ
れたアクションは以下と等価です。
{ print }
これはレコード全体を出力します。
コメントは文字 “#” で始まり、行末まで続きます。空行は、複数ステートメン
トの間をあけるのに使うことができます。通常、ステートメントは改行で終 わ
り ま す 。 ただし、次の記号で行が終わる場合にはこの限りではありません:
“,”, {, ?, :, &&, || 。 do または else で終わる行は、ステートメントが自
動的に以降の行へ継続されます。また、改行の直前に “\” を置くことで、行を
継続することができます。この場合、その改行は無視されます。
“;” で区切ることにより、1行に複数のステートメントを記述することができま
す。 (通常のように) パターン-アクション対中のアクション部におけるステー
トメントだけではなく、パターン-アクション対ステートメント自身も、
“;” で区切って複数置くことができます。
パターン
AWK のパターンは、以下のうちのいずれかです。
BEGIN
END
/regular expression/
relational expression
pattern && pattern
pattern || pattern
pattern ? pattern : pattern
(pattern)
! pattern
pattern1, pattern2
BEGIN と END は特殊なパターンであり、入力と比較されることはありません。
すべての BEGIN パターンに対応したアクション部は結合され、そのようなすべ
てのアクション部が単一の BEGIN ブロック中にあるかのように扱われます。結
合 されたアクションは、すべての入力ファイルの読み込みに先立って実行され
ます。同様にすべての END ブロックは結合され、すべての入力ファイルの処理
後 ( あ る いは、exit ステートメントが実行されたとき) に実行されます。
BEGIN と END はパターン式内で他のパターンと混ぜて使うことはできません。
また、 BEGIN と END パターンはアクション部を省略することができません。
/regular expression/ パターンでは、正規表現 (regular expression) にマッ
チした入力レコードに対してアクションが実行されます。正規表現は egrep(1)
と同じものが使えます。あとに要約を示します。
関 係式(relational expression) では、後述のアクションについての節で示す
演算子を用いることができます。これらは概して、特定のフィールドが正規 表
現にマッチするかどうかを調べるために用いられます。
演 算子 &&, ||, ! は、それぞれ C 言語での論理AND、論理OR、論理NOT と等
価です。 C 言語と同様に、評価値が確定した時点で以降の評価を打ち切ります
。 これらは複数のパターン式を結合するために使用されます。他のプログラミ
ング言語と同様、括弧によって評価順序を変更することができます。
?: 演算子は C 言語のものと同様です。もし、最初のパターンが真なら、テ ス
ト のために 2 番目のパターンが用いられ、そうでなければ 3 番目のパターン
が用いられます。2 番目と 3 番目のパターンのどちらかだけが評価されます。
pattern1, pattern2 形式は 範囲パターンと呼ばれます。範囲パターンは、
pattern1 にマッチするレコードから、 pattern2 にマッチするレコードまでの
す べてにマッチします。この形式は、他のパターン式と混合して用いることは
できません。
正規表現
awk の正規表現は egrep のものと同様に、拡張された正規表現です。以下の構
成要素から成り立っています。
c メタ文字ではない c にマッチします。
\c リテラル文字 c にマッチします。
. 改行を 含む任意の 1 文字にマッチします。
^ 文字列の先頭にマッチします。
$ 文字列の終端にマッチします。
[abc...] 文字リストであり、 abc... のいずれか 1 文字にマッチします。
[^abc...] 文字リストの逆であり、 abc... 以外の 1 文字にマッチします。
r1|r2 選言: r1 または r2 にマッチします。
r1r2 結合: r1 の直後に r2 が続くものにマッチします。
r+ r の 1 回以上の繰り返しにマッチします。
r* r の 0 回以上の繰り返しにマッチします。
r? r の 0 回または 1 回の繰り返しにマッチします。
(r) グループ化: r にマッチします。
r{n}
r{n,}
r{n,m} ブレース中に 1 つか 2 つの数値を記述することにより、 インタ
ーバル表現を表します。ブレース中に数値が 1 つある場合、直 前
の正規表現 r が n 回繰り返されます。2 つの数値がコンマで区切
られている場合、 r は n 回から m 回繰り返されます。1 つの 数
値に続いてコンマがある場合、 r は少なくとも n 回繰り返されま
す。
インターバル表現は --posix または --re-interval がコマンドラ
インにて指定されているときのみ利用可能です。
\y 語の先頭または末尾の空文字列にマッチします。
\B 語の中の空文字列にマッチします。
\< 語の先頭の空文字列にマッチします。
\> 語の末尾の空文字列にマッチします。
\w 語を構成する文字 (レター、数値、アンダスコア) にマッチします
。
\W 語を構成する文字以外の文字にマッチします。
\‘ バッファ (文字列) の先頭の空文字列にマッチします。
\’ バッファの末尾の空文字列にマッチします。
文字列定数中で用いることができるエスケープシーケンス (後述参照) は、 正
規表現中でも使用することができます。
文字クラスは POSIX 標準で導入された新機能です。文字クラスは特定の属性を
持つ文字列リストの特殊表現ですが、実際の文字集合自身は国や文字集合に よ
っ て様々なものとなります。例えば、アルファベット文字はアメリカ合州国と
フランスとでは異なります。
文字クラスが有効なのは、文字リストのブラケットの中の正規表現だけです 。
文 字クラスは、 [: と、クラスを表現するキーワードと、 :] で構成されます
。以下に POSIX 表現で定義される文字クラスを示します。
[:alnum:]
アルファベットと数値文字。
[:alpha:]
アルファベット文字。
[:blank:]
空白とタブ文字。
[:cntrl:]
制御文字。
[:digit:]
数値文字。
[:graph:]
印字可能で可視な文字。 (空白は印字可能ですが見えません。一 方 a
は印字可能かつ可視です。)
[:lower:]
アルファベット文字の小文字。
[:print:]
印字可能な文字 (制御文字以外)。
[:punct:]
句 読 点文字 (レター、数値、制御文字、空白文字のいずれでもない文
字)。
[:space:]
空白文字 (空白、タブ、フォームフィード等の少数の文字を指す)。
[:upper:]
アルファベット文字の大文字。
[:xdigit:]
16 進数の数値。
例えば、POSIX 標準以前では、アルファベットと数値の文字にマッチするた め
には、 /[A-Za-z0-9]/ と書きました。しかし、別のアルファベット文字が文字
集合に含まれる場合、それらにはマッチしません。 POSIX 文字クラスで は 、
/[[:alnum:]]/ と記述することができ、文字集合の すべてのアルファベットと
数値にマッチします。
文字リスト中には、更に 2 つの特殊シーケンスを使用できます。これらは、複
数の文字によって表現される単一シンボル ( 照合文字と呼ばれます) を持ち、
複数の文字が 参照やソートにおいては等価であるとされる、非 ASCII 文字 集
合に適用されます。 (例えば、フランス語では単なる “e” とグレーブアクセン
ト付きの e` とでは等価です。)
照合シンボル
参照シンボルは複数文字の参照要素であり、 [. と .] で括ります。
例 えば、 ch が参照要素の場合、 [[.ch.]] は正規表現となり、この
参照要素にマッチします。一方、 [ch] は c か h にマッチする正規表
現です。
等価クラス
等価クラスは等価な文字リストを指すロケール固有の名前です。名前は
[= と =] で括ります。例えば、名前 e は “e,” “e`,”, “e`.” のす べ
て を 表現するために使用されるかもしれません。この場合、 [[=e=]]
は e, e´, e` のいずれかにマッチする正規表現となります。
これらの機能は英語以外のロケールにて非常に有用です。 gawk が正規表現 の
マッチングに使用するライブラリ関数は、現在 POSIX 文字クラスのみを理解し
、参照シンボルと等価クラスは理解しません。
\y, \B, \<, \>, \w, \W, \‘, \’ の演算子は gawk 固有であり、GNU 正規表現
ライブラリの機能を元にした拡張です。
様 々なコマンドラインオプションによって、正規表現中の文字を gawk がどの
ように解釈するのかを制御できます。
オプション無し
デフォルトでは、 gawk は上述の POSIX 正規表現および GNU 正規表現
のすべての機能を提供します。しかしながら、インターバル表現はサポ
ートされません。
--posix
POSIX 正規表現のみがサポートされ、GNU 演算子はサポートされません
( 例えば、 \w はリテラル w にマッチします)。インターバル表現は許
されます。
--traditional
伝統的な Unix awk の正規表現がサポートされます。GNU 演算子、イン
ターバル表現、 POSIX 文字クラス ( [[:alnum:]] など) はサポートさ
れません。 8 進または 16 進のエスケープシーケンスで表現される 文
字は、正規表現のメタ文字を表現するとしても、リテラルとして扱われ
ます。
--re-interval
--traditional が指定されていたとしても、正規表現中でインターバル
表現をサポートします。
アクション
ア クションは、ブレース { と } で囲みます。アクションは通常の代入、条件
文、ループ文等からなります。演算子、制御文、入出力文は C 言語とほぼ同様
です。
演算子
AWK での演算子を、優先順位の高いものから順に示します。
(...) グループ化。
$ フィールド参照。
++ -- インクリメント、デクリメント。前置も後置も可能。
^ べき乗 (** も同様の意味で使用できる。また **= 代入演算子も
存在する)。
+ - ! 単項のプラス、マイナス、論理否定。
* / % 乗算、除算、剰余。
+ - 加算と減算。
space 文字列結合。
< >
<= >=
!= == 通常の関係演算子。
~ !~ 正規表現マッチ、否定のマッチ。 注意: ~ と !~ の左辺に正規表
現定数 (/foo/等) を用いてはいけません。正規表現定数は右辺に
のみ置くことができます。式 /foo/ ~ exp は (($0 ~ /foo/) ~
exp) と等価であり、これは通常意図するものとは異なります。
in 配列のメンバ。
&& 論理 AND。
|| 論理 OR。
?: C 言語の条件式と同様です。 expr1 ? expr2 : expr3の形式で使
います。もし expr1 が真なら式の値は expr2 になり、そうで な
ければ expr3 になります。 expr2 か expr3 のうち片方のみが評
価されます。
= += -=
*= /= %= ^= 代入。絶対代入 (var = value) と演算子代入 (他の形式) がサポ
ートされています。
制御ステートメント
制御ステートメントは以下のとおりです。
if (condition) statement [ else statement ]
while (condition) statement
do statement while (condition)
for (expr1; expr2; expr3) statement
for (var in array) statement
break
continue
delete array[index]
delete array
exit [ expression ]
{ statements }
入出力ステートメント
入出力ステートメントは以下のとおりです。
close(file) ファイル (またはパイプ、下記参照) をクローズします
。
getline 次のレコードを $0 に読み込みます。 NF, NR, FNR が設
定されます。
getline file
式をファイル file に出力します。各式は OFS の値で区
切られます。出力されるレコードの最後には ORS の値が
付加されます。
printf fmt, expr-list
書式付き出力です。
printf fmt, expr-list >file
ファイル file への書式付き出力です。
system(cmd-line) コマンド cmd-line を実行し、終了ステータスを返し ま
す (POSIX に対応しないシステムでは使用できない場合
があります)。
fflush([file]) オープンされている出力ファイルまたはパイプ file に
関連づけられているバッファをフラッシュします。 file
を指定しないと、標準出力がフラッシュされます。 file
が 空文字列の場合、オープンされているすべてのファイ
ルとパイプのバッファをフラッシュします。
その他の形式のリダイレクトとして以下のものが利用可能です 。 print と
printf に対して、 >> file を指定すると出力はファイル file に追加され、
| command は出力をパイプに対して行います。同様に、 command| getline は
コ マンドの出力から getline を行ないます。 getline はファイル終端では 0
を、エラー時には -1 を返します。
注: ループ中で getline へパイプ書き込みする場合または print か printf
か ら パ イプ読み取りする場合、コマンドの新インスタンスを作成するために
close() を使用することが必要です。パイプが EOF を返すときでも、AWK は自
動的にはパイプを閉じません。
printf ステートメント
AWK での printf ステートメントと sprintf() 関数 (後述参照) は、以下の変
換指定書式を受け付けます。
%c 1 つの ASCII 文字。 %c に対応する引数が数値なら、その値を ASCII
コードとみなして文字に変換します。そうでなければ、引数は文字列で
あると解釈され、その 1 文字目が出力されます。
%d
%i 10 進数 (整数部分)。
%e
%E [-]d.dddddde[+-]dd という形式の浮動小数点数。 %E 形式では e の代
りに E が使用されます。
%f [-]ddd.dddddd という形式の浮動小数点数。
%g
%G %e と %f の短い方の形式の浮動小数点数。余計な 0 は省略されます。
%G 形式では %e の代りに %E を使用します。
%o 符号なしの 8 進数 (整数)。
%u 符号なしの 10 進数 (整数)。
%s 文字列。
%x
%X 符号なしの 16 進数 (整数)。 %X 形式では、 abcdef の代りに ABCDEF
を用います。
%% 単一の文字 % 。引数は使用しません。
% と上記の制御文字との間にオプショナルな追加のパラメータを置くことがで
きます。以下にそれらを示します。
- 左寄せ。
空白 数値変換において、正の値のプレフィックスは空白となり、負の値のプ
レフィックスはマイナス記号となります。
+ プラス記号は幅修正子 (後述) の前に使用し、整形されるデータが正で
あったとしても、数値変換に対して常に符号を付けることを指示します
。 + は空白修正子に優先します。
# ある制御レターに対して「別の形式」を使用します。 %o に対しては先
行する 0 を与え、 %x と %X に対しては非 0 の結果に対して先行する
0x と 0X を与えます。 %e, %E, %f に対しては結果に常に小数点を含
めます。 %g, %G に対しては結果の末尾から 0 を取り除きません。
0 先頭の 0 (ゼロ) はフラグとして動作し、出力を空白ではなく 0 で パ
ディングすることを示します。これは非数値の出力書式に対しても適用
されます。このフラグが有効なのは、フィールド幅が印字される値の幅
より広いときだけです。
width フィールドが指定した幅 width になるようにパディングされます。フ
ィールドは通常空白でパディングされます。 0 フラグが使用された 場
合には 0 でパディングされます。
.prec 印字において使用する精度を数値で指定します。 %e, %E, %f の書式に
対しては、小数点の右側に印字される数字の数を指定します。 %g, %G
の 書 式に対しては、仮数部の最大数を指定します。 %d, %o, %i, %u,
%x, %X の書式に対しては、印字される数字の最小数を指定します。 文
字列に対しては、印字される文字列からとりだされる最大の文字数を指
定します。
ANSI C の printf() の動的な幅 width と精度 prec の指定機能が使用でき ま
す。 幅または 精度の指定部分に * を指定することで、その値を printf また
は sprintf() への引数で指定できます。
特殊ファイル名
print や printf で書き込みときでも、 getline でファイルから読み取るとき
で も、入出力リダイレクトを行う場合、 gawk は内部的な特殊なファイル名を
解釈します。これらのファイル名により、親プロセス (通常はシェルです) か
ら 受け継いだオープン状態のファイルディスクリプタを用いて入出力を行った
り、実行中の gawk プロセスに関する情報を得ることができます。特殊ファ イ
ル名は以下のとおりです。
/dev/pid 現 在のプロセスのプロセスID (10 進数で、最後に改行が付きま
す) を読み込むことができます。
/dev/ppid 現在のプロセスの親のプロセスのプロセスID (10 進数で、最後に
改行が付きます) を読み込むことができます。
/dev/pgrpid 現在のプロセスのプロセスグループ ID (10 進数で、最後に改行
が付きます) を読み込むことができます。
/dev/user このファイルを読むことで、改行で終わる単一のレコードが得 ら
れ ま す 。 各 フ ィ ールドは空白で区切られています。 $1 は
getuid(2) システムコールの値、 $2 は geteuid(2) システム コ
ールの値、 $3 は getgid(2) システムコールの値、 $4 は gete-
gid(2) システムコールの値です。もし、さらにフィールドがあれ
ば 、それは getgroups(2) システムコールが返すグループ ID の
リストです。全てのシステムで複数のグループがサポートされ て
いるわけではありません。
/dev/stdin 標準入力。
/dev/stdout 標準出力。
/dev/stderr 標準エラー出力。
/dev/fd/n オープンされたファイルディスクリプタ n に対応しているファイ
ル。
エラーメッセージを出力するには、以下の方法が便利です。
print "You blew it!" > "/dev/stderr"
もしこの機能が無かったら、次のようにするしかないところです。
print "You blew it!" | "cat 1>&2"
これらのファイル名は、コマンドラインのデータファイル指定で使うことも で
きます。
数値関数
AWK は以下の定義済み数値関数を持っています。
atan2(y, x) y/x の逆正接をラジアンで与えます。
cos(expr) expr の余弦をラジアンで与えます。
exp(expr) 指数関数。
int(expr) 整数への切捨て。
log(expr) 自然対数。
rand() 0 から 1 の間の乱数を与えます。
sin(expr) expr の正弦をラジアンで与えます。
sqrt(expr) 平方根。
srand([expr]) expr の値を乱数生成関数の種として用います。式が指定されな
かった場合は、時刻が用いられます。直前の種の値を返しま す
。
文字列関数
gawk は以下の定義済み文字列関数を持っています。
gensub(r, s, h [, t]) 対象文字列 t から正規表現 r のマッチを探します
。 h が g または G で開始する文字列の場合、マッ
チ する r をすべて s に置き換えます。そうでない
場合、 h は何番目の r のマッチを置き換えるの か
を示します。 t が与えられない場合、代りに $0 が
使用されます。置換テキスト s では、シーケ ン ス
\n ただし n は 1 から 9 までの数字を使用して、
n 番目にマッチした括弧付きサブ式を示すことが で
きます。シーケンス \0 は文字 & と同様、マッチし
たテキスト全体を表します。 sub() や gsub() とは
異 なり、修正された文字列が関数の結果として返さ
れ、元の対象テキストは変更され ません。
gsub(r, s [, t]) 文字列 t 中で正規表現 r にマッチした部分をす べ
て s に置換します。置換の個数を返します。 t を
指定しなかった場合は $0 が用いられます。置換 テ
キストでは、 & は実際にマッチしたテキストで置き
換えられます。 \& を使用するとリテラルの & を得
ることができます。 sub(), gsub(), gensub() にお
ける & とバックスラッシュに関する完全な議 論 は
Effective AWK Language Programming を参照してく
ださい。
index(s, t) 文字列 s 中に含まれる文字列 t の位置を返しま す
。 t が含まれていない場合は 0 を返します。
length([s]) 文字列 s の長さを返します。 s を指定しなかった
場合には $0 の長さを返します。
match(s, r) 文字列 s 中で正規表現 r にマッチする位置を返 し
ま す。マッチしない場合は 0 を返します。 RSTART
と RLENGTH の値が設定されます。
split(s, a [, r]) 文字列 s を正規表現 r を用いて分割し、配列 a に
格納します。フィールド数を返します。 r が省略さ
れた場合は FS が用いられます。配列 a の内容は、
分 割前にクリアされます。分割は、上述のフィール
ド分割と同じ動作を行います。
sprintf(fmt, expr-list) 書式 fmt に従って exp-list を整形表示し、結果の
文字列を返します。
sub(r, s [, t]) gsub() と似ていますが、最初にマッチした文字列の
みが置換されます。
substr(s, i [, n]) 文字列 s の i 文字目から始まる最大 n 文字の部分
文 字列を返します。 n が省略された場合、 i 文字
目以降の部分文字列が返されます。
tolower(str) 文字列 str をコピーし、大文字をすべて小文字に変
換 したものを返します。アルファベットでない文字
は変化しません。
toupper(str) 文字列 str をコピーし、小文字をすべて大文字に変
換 したものを返します。アルファベットでない文字
は変化しません。
時間関数
タイムスタンプを含んだログファイルの処理は AWK プログラムの主な使 い 道
の1つですから、 gawk はタイムスタンプを取り出したり、フォーマットするた
めの 2 つの関数を提供します。
systime() 基準時点からの経過秒数を返します (POSIX システムでは、基準 時
点は UTC で 1970 年 1 月 1 日 0:00 です)。
strftime([format [, timestamp]])
書 式 format に従って timestamp をフォーマットします。 times-
tamp は systime() が返す値と同じ形式でなければなりま せ ん 。
timestamp が省略された場合、現在の日付が使用されます。 format
が省略された場合、 date(1) が出力に使用するものと同じデフォル
ト フォーマットが使用されます。利用可能なフォーマットについて
は、ANSI C の strftime() 関数の仕様を参照して下さい。パブリッ
クドメインな strftime(3) とそのマニュアルページが gawk ととも
に配布されています。もし、 gawk を作成するためにその strftime
を用いた場合は、そのマニュアルに記述されている変換書式が gawk
でも利用可能です。
文字列定数
AWK での文字列定数は、ダブルクォート (") に狭まれた文字の列です。文字列
内では、C 言語のようにいくつかの エスケープシーケンスが使えます。
\\ バックスラッシュそのもの。
\a 「警告」文字。通常は ASCII BEL 文字です。
\b バックスペース。
\f 改ページ (フォームフィード)。
\n 改行。
\r 復帰 (キャリッジリターン)。
\t 水平タブ。
\v 垂直タブ。
\xhex digits
\x に続く 16 進数で表現された文字。ANSI C と同様に、 \x に続くすべ
ての 16 進数字はエスケープシーケンスの一部であるとみなされます。 (
こ の 機能によりコミッティによる言語デザインが分かります。) 例えば
、"\x1B" は ASCII ESC (エスケープ) 文字です。
\ddd 1 桁か 2 桁か 3 桁の 8 進数で表現された文字。例えば、 "\033" は
ASCII ESC (エスケープ) 文字です。
\c 文字 c そのもの。
エ スケープシーケンスは正規表現定数内でも用いることができます (例えば、
/[ \t\f\n\r\v]/ は空白文字にマッチします)。
互換モードでは、8 進および 16 進のエスケープシーケンスで表現される文 字
は 、正規表現定数として使用された場合、リテラルとして扱われます。それゆ
え、 /a\52b/ は /a\*b/ と等価です。
関数
AWK では関数を以下のようにして定義します。
function name(parameter list) { statements }
関数は、パターンまたはアクションの式から呼び出されたときに実行されま す
。 関数呼び出しにおいて与えられた実引数が、関数宣言における仮引数に受け
渡されます。このとき配列の場合は参照渡しが行われ、他の変数の場合は値 渡
しで行われます。
元々 AWK に関数は備わっていませんでしたので、局所変数の機構はあまりスマ
ートではありません。局所変数は引数リストの余分な引数として宣言します 。
局 所変数と関数引数を区別するため、余分な空白で区切るのが慣習です。例え
ば、以下のようにします。
function f(p, q, a, b) # a & b は局所変数
{
...
}
/abc/ { ... ; f(1, 2) ; ... }
関数呼び出しにおける左括弧は、空白を狭まずに関数名の直後に置かなけれ ば
い けません。これは、文字列結合演算子との曖昧さを生じさせないために必要
です。この制限は、上述の組み込み関数にはあてはまりません。
関数は、他の関数を呼び出したり、自分自身を再帰的に呼び出すことができ ま
す。局所変数として用いられる関数引数は、関数起動時に空文字列および 0 に
初期化されます。
関数から値を返すには return expr を使用してください。値を指定しない場合
、 または関数の終りから “落ちる” (訳注: 関数を閉じるブレースに到達する)
ことにより関数から戻る場合、値は未定義です。
--lint が指定されたとき、 gawk は実行時ではなくパーズ時に未定義関数の呼
び 出しに関して警告します。実行時の未定義関数の呼び出しは致命的なエラー
となります。
function のかわりに func を用いることができます。
使用例
“/etc/passwd” から全ユーザのログイン名を取り出し、ソートして出力します。
BEGIN { FS = ":" }
{ print $1 | "sort" }
ファイルの行数を数える。
{ nlines++ }
END { print nlines }
行番号をつける。
{ print FNR, $0 }
全ファイルを通した行番号をつける。
{ print NR, $0 }
関連項目
egrep(1), getpid(2), getppid(2), getpgrp(2), getuid(2), geteuid(2),
getgid(2), getegid(2), getgroups(2)
The AWK Programming Language, Alfred V. Aho, Brian W. Kernighan, Peter
J. Weinberger, Addison-Wesley, 1988. ISBN 0-201-07981-X.
Effective AWK Language Programming, Edition 1.0, published by the Free
Software Foundation, 1995.
POSIX 互換
gawk は最新版の UNIX awk との互換性だけでなく、POSIX 標準との互換性も追
求しています。このため gawk には以下のような機能が取り入れられていま す
。 こ れ ら の 機能は AWK 本には述べられていませんが、 Bell Labs および
POSIX 標準の awk が有している機能です。
プログラム実行前に変数代入を行なう -v オプションは新しい物です。 AWK 本
によれば、コマンドラインで指定された変数代入は awk が引数をファイル名と
してオープンする際に行なわれることになります。つまりこれは BEGIN ブロッ
ク の実行後です。しかしながら初期の頃の実装では、引数の中でファイル名に
先立って変数代入が指定されている場合には、代入は BEGIN ブロック実行の
前 に行われていました。そしてアプリケーションは、この「仕様」に依存する
ようになりました。 awk がそのドキュメントに合うように直された時、昔の動
作 に依存しているアプリケーションの便宜を図るためにこのオプションが加え
られました。 (この仕様は AT&T および GNU の開発者達によって合意されまし
た。)
独自機能のための -W オプションは POSIX 標準に従ったものです。
引 数の列に特別なオプション “--” を指定すると、 gawk はそこがオプション
の終わりであると解釈します。互換モードにおいては未定義オプションは警 告
が 出力され、それ以外のものは無視されます。通常の実行においては残りの引
数は AWK プログラムに引き渡されます。
AWK 本は srand() の返り値を定義していません。 POSIX 標準では、その関 数
が 使っている種を返し、乱数シーケンスを追跡できるようにしています。した
がって gawk における srand() も現在の種を返すようにしてあります。
その他にも以下のような新機能があります。 -f オプションの複数回使用 (MKS
awkに倣いました); ENVIRON 配列; エスケープシーケンス \a と \v ( gawk で
最初に実装され、AT&T の awk にフィードバックされました); 組み込み 関 数
tolower() と toupper() (AT&T に倣いました); printf における ANSI C 変換
指定 (AT&T 版で最初に実装されました)。
GNU 拡張
gawk は POSIX awk に対して多くの拡張が行なわれています。この節ではそ れ
らについて解説します。 --traditional オプション付きで gawk を起動するこ
とによって、ここで述べられている拡張機能をすべて禁止することができま す
。
gawk が持つ以下の機能は POSIX awk では使用できません。
· エスケープシーケンス \x 。( --posix で抑止できます。)
· fflush() 関数。( --posix で抑止できます。)
· systime(), strftime(), gensub() の各関数。
· 入出力リダイレクトで利用可能な特殊ファイル名は理解されません。
· 変数 ARGIND, ERRNO, RT は特殊変数ではありません。
· 変数 IGNORECASE とその副作用は利用できません。
· 変数 FIELDWIDTHS と固定長フィールド分割。
· RS の正規表現としての使用。
· FS に空文字列を設定することにより各文字を切り出 す 能 力 と 、
split() の 3 番目の引数。
· -f オプションで指定されたファイル名についてパス検索を行わない
こと。よって、環境変数 AWKPATH は特殊な変数ではありません。
· 現在の入力ファイルに対する処理を終わらせるために使 用 さ れ る
nextfile 。
· 配列全体を削除するために使用される delete 配列。
AWK 本は関数 close() の返り値を定義していません。 gawk の close() は、
ファイルやパイプをクローズする際に呼び出す fclose(3) や pclose(3)、から
の返り値を返します。
オ プション --traditional 付きで gawk を起動し -F オプションへの引数 fs
として “t” を与えた場合に、 FS の値はタブ文字に設定されます。 gawk -F\t
... とタイプしても、シェルが単に “t” をクォートするので、“\t” は -F オ
プションに渡されません。これは少々見苦しい特殊事例ですので、デフォル ト
の動作としては採用されていません。 --posix を指定した場合にも、この動作
は行なわれません。タブ文字をフィールドセパレータとして使用したい場合 に
は、クォートを使用するのが最良です: gawk -F’\t’ ....
歴史的機能
gawk は歴代の AWK の実装にあった 2 つの機能を備えています。 1 つめとし
て、組み込み関数 length() は引数無しで呼び出せるだけでなく、さらに括 弧
無しでも呼び出せます! したがって
a = length # Holy Algol 60, Batman!
は以下の2例と同じです。
a = length()
a = length($0)
POSIX 標準ではこの機能は “deprecated” と注意書きされており、 gawk では
コマンドラインで --lint を指定した場合に、この機能の使用に対して警告 を
出力します。
も う 1 つは、 while, for, do ループ本体の外でも continue, break ステー
トメントを使用できるという機能です。伝統的な AWK の実装では、このように
使 用した continue ステートメントを next ステートメントと等価なものとし
て扱ってきました。 gawk では --traditional が指定された場合に、この機能
を使うことができます。
環境変数
環 境 に POSIXLY_CORRECT が存在する場合には、 gawk はコマンドラインで
--posix が指定されている時と全く同じ動作をします。このとき --lint が 指
定されていると gawk はこの作用についての警告メッセージを出力します。
AWKPATH 環境変数を使用して、 gawk が -f および --file オプションで指定
されたファイル名を検索するディレクトリを指定できます。
バグ
コマンドラインでの変数代入機能を使用するには、変数への代入を直接コマ ン
ド ラインに書けばよく、 -F オプションをつける必要はありません。このオプ
ションは昔の awk との互換性のためだけに残されています。
ファイル /dev/fd および /dev/stdin, /dev/stdout, /dev/stderr を実際にサ
ポ ートしているシステムでの gawk からは、それらがないシステムとは違った
出力が得られるかもしれません。 gawk はそれらのファイルを内部で解釈す る
際に標準出力への出力を /dev/stdout への出力と同期させますが、それらのフ
ァイルを持つシステムでは出力はそれぞれ異なるファイルへ向けられます。 利
用者の方で気を付けるようにしてください (Caveat Emptor)。
文 法的に誤った単一文字プログラムはパーズスタックを溢れさせる傾向があり
、まったく分からないメッセージを生成する傾向にあります。このようなプ ロ
グ ラムの診断は驚くべきことに一般に難しく、診断の努力はまったく無意味に
なります。
バージョン情報
このマニュアルは gawk バージョン 3.0.6 について記載しています。
作者
UNIX awk の最初のバージョンは、AT&T Bell Labs の Alfred Aho と Peter
Weinberger および Brian Kernighan によって設計、実装されました。 Brian
Kernighan はその保守と改良を続けています。
Free Software Foundation の Paul Rubin と Jay Fenlason が、Seventh Edi-
tion UNIX で配布された最初のバージョンの awk と互換性を持つように gawk
を書きました。 John Woods は数々のバグ修正を送って下さいました。 David
Trueman は、Arnold Robbins が送って下さった内容をもとに、 gawk を新バー
ジョンの UNIX awk 互換にしました。
DOS への最初の移植は Conrad Kwok と Scott Garfinkle によって行なわれ ま
し た 。現在は Scott Deifik が DOS 版の保守をしています。 Pat Rankin は
VMS への移植を行ない、Michal Jaegermann は Atari ST への移植を行ない ま
し た。 OS/2 への移植は Kai Uwe Rommel が Darrel Hankerson の助けを借り
て行ないました。 Fred Fish が Amiga サポートの提供を行いました。
バグレポート
gawk のバグを見付けたら、電子メールを bug-gawk@gnu.org 宛に送ってくださ
い 。電子メールには、オペレーティングシステムとそのリビジョン、 gawk の
リビジョン、コンパイルに使用した C コンパイラ、問題を再現するできるだけ
小さなテストプログラムとデータを記述してください。
バグレポートを送る前に 2 つのことを行ってください。第 1 に、最新の gawk
を使用されていることを確認してください。多くの (通常微妙な) バグが各 々
の リリースで修正されていますので、ご使用のものが古い場合には問題は既に
解決されているかもしれません。第 2 に、このマニュアルページとリファレン
ス マニュアルを注意深く読み、あなたがバグだと思うものが確かにバグであり
、大きく変わった言語仕様ではないことを確認してください。
バグレポートを comp.lang.awk に投稿することだけはしないでく だ さ い 。
gawk の開発者達は時々このニュースグループを読みますが、バグレポートをこ
のニュースグループに投稿してもバグレポートとして信頼性がありません。 上
記のアドレスへの電子メールでお願いします。
謝辞
Bell Labs の Brian Kernighan はテストおよびデバッグの間、貴重な助力を提
供して下さいました。感謝致します。
COPYING PERMISSIONS
Copyright © 1996-2000 Free Software Foundation, Inc.
Permission is granted to make and distribute verbatim copies of this
manual page provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual page under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
Permission is granted to copy and distribute translations of this man-
ual page into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a trans-
lation approved by the Foundation.
Free Software Foundation May 17 2000 GAWK(1)
GAWK(1) Utility Commands GAWK(1)
NAME
gawk - pattern scanning and processing language
SYNOPSIS
gawk [ POSIX or GNU style options ] -f program-file [ -- ] file ...
gawk [ POSIX or GNU style options ] [ -- ] program-text file ...
pgawk [ POSIX or GNU style options ] -f program-file [ -- ] file ...
pgawk [ POSIX or GNU style options ] [ -- ] program-text file ...
DESCRIPTION
Gawk is the GNU Project’s implementation of the AWK programming lan-
guage. It conforms to the definition of the language in the POSIX
1003.1 Standard. This version in turn is based on the description in
The AWK Programming Language, by Aho, Kernighan, and Weinberger, with
the additional features found in the System V Release 4 version of UNIX
awk. Gawk also provides more recent Bell Laboratories awk extensions,
and a number of GNU-specific extensions.
Pgawk is the profiling version of gawk. It is identical in every way
to gawk, except that programs run more slowly, and it automatically
produces an execution profile in the file awkprof.out when done. See
the --profile option, below.
The command line consists of options to gawk itself, the AWK program
text (if not supplied via the -f or --file options), and values to be
made available in the ARGC and ARGV pre-defined AWK variables.
OPTION FORMAT
Gawk options may be either traditional POSIX one letter options, or
GNU-style long options. POSIX options start with a single “-”, while
long options start with “--”. Long options are provided for both GNU-
specific features and for POSIX-mandated features.
Following the POSIX standard, gawk-specific options are supplied via
arguments to the -W option. Multiple -W options may be supplied Each
-W option has a corresponding long option, as detailed below. Argu-
ments to long options are either joined with the option by an = sign,
with no intervening spaces, or they may be provided in the next command
line argument. Long options may be abbreviated, as long as the abbre-
viation remains unique.
OPTIONS
Gawk accepts the following options, listed by frequency.
-F fs
--field-separator fs
Use fs for the input field separator (the value of the FS prede-
fined variable).
-v var=val
--assign var=val
Assign the value val to the variable var, before execution of
the program begins. Such variable values are available to the
BEGIN block of an AWK program.
-f program-file
--file program-file
Read the AWK program source from the file program-file, instead
of from the first command line argument. Multiple -f (or
--file) options may be used.
-mf NNN
-mr NNN
Set various memory limits to the value NNN. The f flag sets the
maximum number of fields, and the r flag sets the maximum record
size. These two flags and the -m option are from an earlier
version of the Bell Laboratories research version of UNIX awk.
They are ignored by gawk, since gawk has no pre-defined limits.
(Current versions of the Bell Laboratories awk no longer accept
them.)
-O
--optimize
Enable optimizations upon the internal representation of the
program. Currently, this includes just simple constant-folding.
The gawk maintainer hopes to add additional optimizations over
time.
-W compat
-W traditional
--compat
--traditional
Run in compatibility mode. In compatibility mode, gawk behaves
identically to UNIX awk; none of the GNU-specific extensions are
recognized. The use of --traditional is preferred over the
other forms of this option. See GNU EXTENSIONS, below, for more
information.
-W copyleft
-W copyright
--copyleft
--copyright
Print the short version of the GNU copyright information message
on the standard output and exit successfully.
-W dump-variables[=file]
--dump-variables[=file]
Print a sorted list of global variables, their types and final
values to file. If no file is provided, gawk uses a file named
awkvars.out in the current directory.
Having a list of all the global variables is a good way to look
for typographical errors in your programs. You would also use
this option if you have a large program with a lot of functions,
and you want to be sure that your functions don’t inadvertently
use global variables that you meant to be local. (This is a
particularly easy mistake to make with simple variable names
like i, j, and so on.)
-W exec file
--exec file
Similar to -f, however, this is option is the last one pro-
cessed. This should be used with #! scripts, particularly for
CGI applications, to avoid passing in options or source code (!)
on the command line from a URL. This option disables command-
line variable assignments.
-W gen-po
--gen-po
Scan and parse the AWK program, and generate a GNU .po format
file on standard output with entries for all localizable strings
in the program. The program itself is not executed. See the
GNU gettext distribution for more information on .po files.
-W help
-W usage
--help
--usage
Print a relatively short summary of the available options on the
standard output. (Per the GNU Coding Standards, these options
cause an immediate, successful exit.)
-W lint[=value]
--lint[=value]
Provide warnings about constructs that are dubious or non-
portable to other AWK implementations. With an optional argu-
ment of fatal, lint warnings become fatal errors. This may be
drastic, but its use will certainly encourage the development of
cleaner AWK programs. With an optional argument of invalid,
only warnings about things that are actually invalid are issued.
(This is not fully implemented yet.)
-W lint-old
--lint-old
Provide warnings about constructs that are not portable to the
original version of Unix awk.
-W non-decimal-data
--non-decimal-data
Recognize octal and hexadecimal values in input data. Use this
option with great caution!
-W posix
--posix
This turns on compatibility mode, with the following additional
restrictions:
· \x escape sequences are not recognized.
· Only space and tab act as field separators when FS is set to a
single space, newline does not.
· You cannot continue lines after ? and :.
· The synonym func for the keyword function is not recognized.
· The operators ** and **= cannot be used in place of ^ and ^=.
· The fflush() function is not available.
-W profile[=prof_file]
--profile[=prof_file]
Send profiling data to prof_file. The default is awkprof.out.
When run with gawk, the profile is just a “pretty printed” ver-
sion of the program. When run with pgawk, the profile contains
execution counts of each statement in the program in the left
margin and function call counts for each user-defined function.
-W re-interval
--re-interval
Enable the use of interval expressions in regular expression
matching (see Regular Expressions, below). Interval expressions
were not traditionally available in the AWK language. The POSIX
standard added them, to make awk and egrep consistent with each
other. However, their use is likely to break old AWK programs,
so gawk only provides them if they are requested with this
option, or when --posix is specified.
-W source program-text
--source program-text
Use program-text as AWK program source code. This option allows
the easy intermixing of library functions (used via the -f and
--file options) with source code entered on the command line.
It is intended primarily for medium to large AWK programs used
in shell scripts.
-W use-lc-numeric
--use-lc-numeric
This forces gawk to use the locale’s decimal point character
when parsing input data. Although the POSIX standard requires
this behavior, and gawk does so when --posix is in effect, the
default is to follow traditional behavior and use a period as
the decimal point, even in locales where the period is not the
decimal point character. This option overrides the default
behavior, without the full draconian strictness of the --posix
option.
-W version
--version
Print version information for this particular copy of gawk on
the standard output. This is useful mainly for knowing if the
current copy of gawk on your system is up to date with respect
to whatever the Free Software Foundation is distributing. This
is also useful when reporting bugs. (Per the GNU Coding Stan-
dards, these options cause an immediate, successful exit.)
-- Signal the end of options. This is useful to allow further argu-
ments to the AWK program itself to start with a “-”. This pro-
vides consistency with the argument parsing convention used by
most other POSIX programs.
In compatibility mode, any other options are flagged as invalid, but
are otherwise ignored. In normal operation, as long as program text
has been supplied, unknown options are passed on to the AWK program in
the ARGV array for processing. This is particularly useful for running
AWK programs via the “#!” executable interpreter mechanism.
AWK PROGRAM EXECUTION
An AWK program consists of a sequence of pattern-action statements and
optional function definitions.
pattern { action statements }
function name(parameter list) { statements }
Gawk first reads the program source from the program-file(s) if speci-
fied, from arguments to --source, or from the first non-option argument
on the command line. The -f and --source options may be used multiple
times on the command line. Gawk reads the program text as if all the
program-files and command line source texts had been concatenated
together. This is useful for building libraries of AWK functions,
without having to include them in each new AWK program that uses them.
It also provides the ability to mix library functions with command line
programs.
The environment variable AWKPATH specifies a search path to use when
finding source files named with the -f option. If this variable does
not exist, the default path is ".:/usr/local/share/awk". (The actual
directory may vary, depending upon how gawk was built and installed.)
If a file name given to the -f option contains a “/” character, no path
search is performed.
Gawk executes AWK programs in the following order. First, all variable
assignments specified via the -v option are performed. Next, gawk com-
piles the program into an internal form. Then, gawk executes the code
in the BEGIN block(s) (if any), and then proceeds to read each file
named in the ARGV array. If there are no files named on the command
line, gawk reads the standard input.
If a filename on the command line has the form var=val it is treated as
a variable assignment. The variable var will be assigned the value
val. (This happens after any BEGIN block(s) have been run.) Command
line variable assignment is most useful for dynamically assigning val-
ues to the variables AWK uses to control how input is broken into
fields and records. It is also useful for controlling state if multi-
ple passes are needed over a single data file.
If the value of a particular element of ARGV is empty (""), gawk skips
over it.
For each record in the input, gawk tests to see if it matches any
pattern in the AWK program. For each pattern that the record matches,
the associated action is executed. The patterns are tested in the
order they occur in the program.
Finally, after all the input is exhausted, gawk executes the code in
the END block(s) (if any).
VARIABLES, RECORDS AND FIELDS
AWK variables are dynamic; they come into existence when they are first
used. Their values are either floating-point numbers or strings, or
both, depending upon how they are used. AWK also has one dimensional
arrays; arrays with multiple dimensions may be simulated. Several pre-
defined variables are set as a program runs; these are described as
needed and summarized below.
Records
Normally, records are separated by newline characters. You can control
how records are separated by assigning values to the built-in variable
RS. If RS is any single character, that character separates records.
Otherwise, RS is a regular expression. Text in the input that matches
this regular expression separates the record. However, in compatibil-
ity mode, only the first character of its string value is used for sep-
arating records. If RS is set to the null string, then records are
separated by blank lines. When RS is set to the null string, the new-
line character always acts as a field separator, in addition to what-
ever value FS may have.
Fields
As each input record is read, gawk splits the record into fields, using
the value of the FS variable as the field separator. If FS is a single
character, fields are separated by that character. If FS is the null
string, then each individual character becomes a separate field. Oth-
erwise, FS is expected to be a full regular expression. In the special
case that FS is a single space, fields are separated by runs of spaces
and/or tabs and/or newlines. (But see the section POSIX COMPATIBILITY,
below). NOTE: The value of IGNORECASE (see below) also affects how
fields are split when FS is a regular expression, and how records are
separated when RS is a regular expression.
If the FIELDWIDTHS variable is set to a space separated list of num-
bers, each field is expected to have fixed width, and gawk splits up
the record using the specified widths. The value of FS is ignored.
Assigning a new value to FS overrides the use of FIELDWIDTHS, and
restores the default behavior.
Each field in the input record may be referenced by its position, $1,
$2, and so on. $0 is the whole record. Fields need not be referenced
by constants:
n = 5
print $n
prints the fifth field in the input record.
The variable NF is set to the total number of fields in the input
record.
References to non-existent fields (i.e. fields after $NF) produce the
null-string. However, assigning to a non-existent field (e.g., $(NF+2)
= 5) increases the value of NF, creates any intervening fields with the
null string as their value, and causes the value of $0 to be recom-
puted, with the fields being separated by the value of OFS. References
to negative numbered fields cause a fatal error. Decrementing NF
causes the values of fields past the new value to be lost, and the
value of $0 to be recomputed, with the fields being separated by the
value of OFS.
Assigning a value to an existing field causes the whole record to be
rebuilt when $0 is referenced. Similarly, assigning a value to $0
causes the record to be resplit, creating new values for the fields.
Built-in Variables
Gawk’s built-in variables are:
ARGC The number of command line arguments (does not include
options to gawk, or the program source).
ARGIND The index in ARGV of the current file being processed.
ARGV Array of command line arguments. The array is indexed from
0 to ARGC - 1. Dynamically changing the contents of ARGV
can control the files used for data.
BINMODE On non-POSIX systems, specifies use of “binary” mode for
all file I/O. Numeric values of 1, 2, or 3, specify that
input files, output files, or all files, respectively,
should use binary I/O. String values of "r", or "w" spec-
ify that input files, or output files, respectively, should
use binary I/O. String values of "rw" or "wr" specify that
all files should use binary I/O. Any other string value is
treated as "rw", but generates a warning message.
CONVFMT The conversion format for numbers, "%.6g", by default.
ENVIRON An array containing the values of the current environment.
The array is indexed by the environment variables, each
element being the value of that variable (e.g., ENVI-
RON["HOME"] might be /home/arnold). Changing this array
does not affect the environment seen by programs which gawk
spawns via redirection or the system() function.
ERRNO If a system error occurs either doing a redirection for
getline, during a read for getline, or during a close(),
then ERRNO will contain a string describing the error. The
value is subject to translation in non-English locales.
FIELDWIDTHS A white-space separated list of fieldwidths. When set,
gawk parses the input into fields of fixed width, instead
of using the value of the FS variable as the field separa-
tor.
FILENAME The name of the current input file. If no files are speci-
fied on the command line, the value of FILENAME is “-”.
However, FILENAME is undefined inside the BEGIN block
(unless set by getline).
FNR The input record number in the current input file.
FS The input field separator, a space by default. See Fields,
above.
IGNORECASE Controls the case-sensitivity of all regular expression and
string operations. If IGNORECASE has a non-zero value,
then string comparisons and pattern matching in rules,
field splitting with FS, record separating with RS, regular
expression matching with ~ and !~, and the gensub(),
gsub(), index(), match(), split(), and sub() built-in func-
tions all ignore case when doing regular expression opera-
tions. NOTE: Array subscripting is not affected. However,
the asort() and asorti() functions are affected.
Thus, if IGNORECASE is not equal to zero, /aB/ matches all
of the strings "ab", "aB", "Ab", and "AB". As with all AWK
variables, the initial value of IGNORECASE is zero, so all
regular expression and string operations are normally case-
sensitive. Under Unix, the full ISO 8859-1 Latin-1 charac-
ter set is used when ignoring case. As of gawk 3.1.4, the
case equivalencies are fully locale-aware, based on the C
facilities such as isalpha(), and toupper().
LINT Provides dynamic control of the --lint option from within
an AWK program. When true, gawk prints lint warnings. When
false, it does not. When assigned the string value
"fatal", lint warnings become fatal errors, exactly like
--lint=fatal. Any other true value just prints warnings.
NF The number of fields in the current input record.
NR The total number of input records seen so far.
OFMT The output format for numbers, "%.6g", by default.
OFS The output field separator, a space by default.
ORS The output record separator, by default a newline.
PROCINFO The elements of this array provide access to information
about the running AWK program. On some systems, there may
be elements in the array, "group1" through "groupn" for
some n, which is the number of supplementary groups that
the process has. Use the in operator to test for these
elements. The following elements are guaranteed to be
available:
PROCINFO["egid"] the value of the getegid(2) system call.
PROCINFO["euid"] the value of the geteuid(2) system call.
PROCINFO["FS"] "FS" if field splitting with FS is in
effect, or "FIELDWIDTHS" if field split-
ting with FIELDWIDTHS is in effect.
PROCINFO["gid"] the value of the getgid(2) system call.
PROCINFO["pgrpid"] the process group ID of the current pro-
cess.
PROCINFO["pid"] the process ID of the current process.
PROCINFO["ppid"] the parent process ID of the current
process.
PROCINFO["uid"] the value of the getuid(2) system call.
PROCINFO["version"]
The version of gawk. This is available
from version 3.1.4 and later.
RS The input record separator, by default a newline.
RT The record terminator. Gawk sets RT to the input text that
matched the character or regular expression specified by
RS.
RSTART The index of the first character matched by match(); 0 if
no match. (This implies that character indices start at
one.)
RLENGTH The length of the string matched by match(); -1 if no
match.
SUBSEP The character used to separate multiple subscripts in array
elements, by default "\034".
TEXTDOMAIN The text domain of the AWK program; used to find the local-
ized translations for the program’s strings.
Arrays
Arrays are subscripted with an expression between square brackets ([
and ]). If the expression is an expression list (expr, expr ...) then
the array subscript is a string consisting of the concatenation of the
(string) value of each expression, separated by the value of the SUBSEP
variable. This facility is used to simulate multiply dimensioned
arrays. For example:
i = "A"; j = "B"; k = "C"
x[i, j, k] = "hello, world\n"
assigns the string "hello, world\n" to the element of the array x which
is indexed by the string "A\034B\034C". All arrays in AWK are associa-
tive, i.e. indexed by string values.
The special operator in may be used to test if an array has an index
consisting of a particular value.
if (val in array)
print array[val]
If the array has multiple subscripts, use (i, j) in array.
The in construct may also be used in a for loop to iterate over all the
elements of an array.
An element may be deleted from an array using the delete statement.
The delete statement may also be used to delete the entire contents of
an array, just by specifying the array name without a subscript.
Variable Typing And Conversion
Variables and fields may be (floating point) numbers, or strings, or
both. How the value of a variable is interpreted depends upon its con-
text. If used in a numeric expression, it will be treated as a number;
if used as a string it will be treated as a string.
To force a variable to be treated as a number, add 0 to it; to force it
to be treated as a string, concatenate it with the null string.
When a string must be converted to a number, the conversion is accom-
plished using strtod(3). A number is converted to a string by using
the value of CONVFMT as a format string for sprintf(3), with the
numeric value of the variable as the argument. However, even though
all numbers in AWK are floating-point, integral values are always con-
verted as integers. Thus, given
CONVFMT = "%2.2f"
a = 12
b = a ""
the variable b has a string value of "12" and not "12.00".
When operating in POSIX mode (such as with the --posix command line
option), beware that locale settings may interfere with the way decimal
numbers are treated: the decimal separator of the numbers you are feed-
ing to gawk must conform to what your locale would expect, be it a
comma (,) or a period (.).
Gawk performs comparisons as follows: If two variables are numeric,
they are compared numerically. If one value is numeric and the other
has a string value that is a “numeric string,” then comparisons are
also done numerically. Otherwise, the numeric value is converted to a
string and a string comparison is performed. Two strings are compared,
of course, as strings.
Note that string constants, such as "57", are not numeric strings, they
are string constants. The idea of “numeric string” only applies to
fields, getline input, FILENAME, ARGV elements, ENVIRON elements and
the elements of an array created by split() that are numeric strings.
The basic idea is that user input, and only user input, that looks
numeric, should be treated that way.
Uninitialized variables have the numeric value 0 and the string value
"" (the null, or empty, string).
Octal and Hexadecimal Constants
Starting with version 3.1 of gawk , you may use C-style octal and hex-
adecimal constants in your AWK program source code. For example, the
octal value 011 is equal to decimal 9, and the hexadecimal value 0x11
is equal to decimal 17.
String Constants
String constants in AWK are sequences of characters enclosed between
double quotes ("). Within strings, certain escape sequences are recog-
nized, as in C. These are:
\\ A literal backslash.
\a The “alert” character; usually the ASCII BEL character.
\b backspace.
\f form-feed.
\n newline.
\r carriage return.
\t horizontal tab.
\v vertical tab.
\xhex digits
The character represented by the string of hexadecimal digits fol-
lowing the \x. As in ANSI C, all following hexadecimal digits are
considered part of the escape sequence. (This feature should tell
us something about language design by committee.) E.g., "\x1B" is
the ASCII ESC (escape) character.
\ddd The character represented by the 1-, 2-, or 3-digit sequence of
octal digits. E.g., "\033" is the ASCII ESC (escape) character.
\c The literal character c.
The escape sequences may also be used inside constant regular expres-
sions (e.g., /[ \t\f\n\r\v]/ matches whitespace characters).
In compatibility mode, the characters represented by octal and hexadec-
imal escape sequences are treated literally when used in regular
expression constants. Thus, /a\52b/ is equivalent to /a\*b/.
PATTERNS AND ACTIONS
AWK is a line-oriented language. The pattern comes first, and then the
action. Action statements are enclosed in { and }. Either the pattern
may be missing, or the action may be missing, but, of course, not both.
If the pattern is missing, the action is executed for every single
record of input. A missing action is equivalent to
{ print }
which prints the entire record.
Comments begin with the “#” character, and continue until the end of
the line. Blank lines may be used to separate statements. Normally, a
statement ends with a newline, however, this is not the case for lines
ending in a “,”, {, ?, :, &&, or ||. Lines ending in do or else also
have their statements automatically continued on the following line.
In other cases, a line can be continued by ending it with a “\”, in
which case the newline will be ignored.
Multiple statements may be put on one line by separating them with a
“;”. This applies to both the statements within the action part of a
pattern-action pair (the usual case), and to the pattern-action state-
ments themselves.
Patterns
AWK patterns may be one of the following:
BEGIN
END
/regular expression/
relational expression
pattern && pattern
pattern || pattern
pattern ? pattern : pattern
(pattern)
! pattern
pattern1, pattern2
BEGIN and END are two special kinds of patterns which are not tested
against the input. The action parts of all BEGIN patterns are merged
as if all the statements had been written in a single BEGIN block.
They are executed before any of the input is read. Similarly, all the
END blocks are merged, and executed when all the input is exhausted (or
when an exit statement is executed). BEGIN and END patterns cannot be
combined with other patterns in pattern expressions. BEGIN and END
patterns cannot have missing action parts.
For /regular expression/ patterns, the associated statement is executed
for each input record that matches the regular expression. Regular
expressions are the same as those in egrep(1), and are summarized
below.
A relational expression may use any of the operators defined below in
the section on actions. These generally test whether certain fields
match certain regular expressions.
The &&, ||, and ! operators are logical AND, logical OR, and logical
NOT, respectively, as in C. They do short-circuit evaluation, also as
in C, and are used for combining more primitive pattern expressions.
As in most languages, parentheses may be used to change the order of
evaluation.
The ?: operator is like the same operator in C. If the first pattern
is true then the pattern used for testing is the second pattern, other-
wise it is the third. Only one of the second and third patterns is
evaluated.
The pattern1, pattern2 form of an expression is called a range pattern.
It matches all input records starting with a record that matches pat-
tern1, and continuing until a record that matches pattern2, inclusive.
It does not combine with any other sort of pattern expression.
Regular Expressions
Regular expressions are the extended kind found in egrep. They are
composed of characters as follows:
c matches the non-metacharacter c.
\c matches the literal character c.
. matches any character including newline.
^ matches the beginning of a string.
$ matches the end of a string.
[abc...] character list, matches any of the characters abc....
[^abc...] negated character list, matches any character except abc....
r1|r2 alternation: matches either r1 or r2.
r1r2 concatenation: matches r1, and then r2.
r+ matches one or more r’s.
r* matches zero or more r’s.
r? matches zero or one r’s.
(r) grouping: matches r.
r{n}
r{n,}
r{n,m} One or two numbers inside braces denote an interval expres-
sion. If there is one number in the braces, the preceding
regular expression r is repeated n times. If there are two
numbers separated by a comma, r is repeated n to m times.
If there is one number followed by a comma, then r is
repeated at least n times.
Interval expressions are only available if either --posix or
--re-interval is specified on the command line.
\y matches the empty string at either the beginning or the end
of a word.
\B matches the empty string within a word.
\< matches the empty string at the beginning of a word.
\> matches the empty string at the end of a word.
\w matches any word-constituent character (letter, digit, or
underscore).
\W matches any character that is not word-constituent.
\‘ matches the empty string at the beginning of a buffer
(string).
\’ matches the empty string at the end of a buffer.
The escape sequences that are valid in string constants (see below) are
also valid in regular expressions.
Character classes are a feature introduced in the POSIX standard. A
character class is a special notation for describing lists of charac-
ters that have a specific attribute, but where the actual characters
themselves can vary from country to country and/or from character set
to character set. For example, the notion of what is an alphabetic
character differs in the USA and in France.
A character class is only valid in a regular expression inside the
brackets of a character list. Character classes consist of [:, a key-
word denoting the class, and :]. The character classes defined by the
POSIX standard are:
[:alnum:] Alphanumeric characters.
[:alpha:] Alphabetic characters.
[:blank:] Space or tab characters.
[:cntrl:] Control characters.
[:digit:] Numeric characters.
[:graph:] Characters that are both printable and visible. (A space is
printable, but not visible, while an a is both.)
[:lower:] Lower-case alphabetic characters.
[:print:] Printable characters (characters that are not control char-
acters.)
[:punct:] Punctuation characters (characters that are not letter, dig-
its, control characters, or space characters).
[:space:] Space characters (such as space, tab, and formfeed, to name
a few).
[:upper:] Upper-case alphabetic characters.
[:xdigit:] Characters that are hexadecimal digits.
For example, before the POSIX standard, to match alphanumeric charac-
ters, you would have had to write /[A-Za-z0-9]/. If your character set
had other alphabetic characters in it, this would not match them, and
if your character set collated differently from ASCII, this might not
even match the ASCII alphanumeric characters. With the POSIX character
classes, you can write /[[:alnum:]]/, and this matches the alphabetic
and numeric characters in your character set, no matter what it is.
Two additional special sequences can appear in character lists. These
apply to non-ASCII character sets, which can have single symbols
(called collating elements) that are represented with more than one
character, as well as several characters that are equivalent for col-
lating, or sorting, purposes. (E.g., in French, a plain “e” and a
grave-accented “`” are equivalent.)
Collating Symbols
A collating symbol is a multi-character collating element
enclosed in [. and .]. For example, if ch is a collating ele-
ment, then [[.ch.]] is a regular expression that matches this
collating element, while [ch] is a regular expression that
matches either c or h.
Equivalence Classes
An equivalence class is a locale-specific name for a list of
characters that are equivalent. The name is enclosed in [= and
=]. For example, the name e might be used to represent all of
“e,” “´,” and “`.” In this case, [[=e=]] is a regular expres-
sion that matches any of e, ´, or `.
These features are very valuable in non-English speaking locales. The
library functions that gawk uses for regular expression matching cur-
rently only recognize POSIX character classes; they do not recognize
collating symbols or equivalence classes.
The \y, \B, \<, \>, \w, \W, \‘, and \’ operators are specific to gawk;
they are extensions based on facilities in the GNU regular expression
libraries.
The various command line options control how gawk interprets characters
in regular expressions.
No options
In the default case, gawk provide all the facilities of POSIX
regular expressions and the GNU regular expression operators
described above. However, interval expressions are not sup-
ported.
--posix
Only POSIX regular expressions are supported, the GNU operators
are not special. (E.g., \w matches a literal w). Interval
expressions are allowed. PLEASE NOTE that the regular expression
[A-Z] will also match the lowercase characters in this case!
Consult the info pages of gawk utility for more information
about this behaviour.
--traditional
Traditional Unix awk regular expressions are matched. The GNU
operators are not special, interval expressions are not avail-
able, and neither are the POSIX character classes ([[:alnum:]]
and so on). Characters described by octal and hexadecimal
escape sequences are treated literally, even if they represent
regular expression metacharacters.
--re-interval
Allow interval expressions in regular expressions, even if
--traditional has been provided.
Actions
Action statements are enclosed in braces, { and }. Action statements
consist of the usual assignment, conditional, and looping statements
found in most languages. The operators, control statements, and
input/output statements available are patterned after those in C.
Operators
The operators in AWK, in order of decreasing precedence, are
(...) Grouping
$ Field reference.
++ -- Increment and decrement, both prefix and postfix.
^ Exponentiation (** may also be used, and **= for the
assignment operator).
+ - ! Unary plus, unary minus, and logical negation.
* / % Multiplication, division, and modulus.
+ - Addition and subtraction.
space String concatenation.
| |& Piped I/O for getline, print, and printf.
< >
<= >=
!= == The regular relational operators.
~ !~ Regular expression match, negated match. NOTE: Do not use
a constant regular expression (/foo/) on the left-hand side
of a ~ or !~. Only use one on the right-hand side. The
expression /foo/ ~ exp has the same meaning as (($0 ~
/foo/) ~ exp). This is usually not what was intended.
in Array membership.
&& Logical AND.
|| Logical OR.
?: The C conditional expression. This has the form expr1 ?
expr2 : expr3. If expr1 is true, the value of the expres-
sion is expr2, otherwise it is expr3. Only one of expr2
and expr3 is evaluated.
= += -=
*= /= %= ^= Assignment. Both absolute assignment (var = value) and
operator-assignment (the other forms) are supported.
Control Statements
The control statements are as follows:
if (condition) statement [ else statement ]
while (condition) statement
do statement while (condition)
for (expr1; expr2; expr3) statement
for (var in array) statement
break
continue
delete array[index]
delete array
exit [ expression ]
{ statements }
I/O Statements
The input/output statements are as follows:
close(file [, how]) Close file, pipe or co-process. The optional how
should only be used when closing one end of a
two-way pipe to a co-process. It must be a
string value, either "to" or "from".
getline Set $0 from next input record; set NF, NR, FNR.
getline file Prints expressions on file. Each expression is
separated by the value of the OFS variable. The
output record is terminated with the value of the
ORS variable.
printf fmt, expr-list Format and print.
printf fmt, expr-list >file
Format and print on file.
system(cmd-line) Execute the command cmd-line, and return the exit
status. (This may not be available on non-POSIX
systems.)
fflush([file]) Flush any buffers associated with the open output
file or pipe file. If file is missing, then
standard output is flushed. If file is the null
string, then all open output files and pipes have
their buffers flushed.
Additional output redirections are allowed for print and printf.
print ... >> file
Appends output to the file.
print ... | command
Writes on a pipe.
print ... |& command
Sends data to a co-process or socket. (See also the subsection
Special File Names, below.)
The getline command returns 1 on success, 0 on end of file, and -1 on
an error. Upon an error, ERRNO contains a string describing the prob-
lem.
NOTE: If using a pipe, co-process, or socket to getline, or from print
or printf within a loop, you must use close() to create new instances
of the command or socket. AWK does not automatically close pipes,
sockets, or co-processes when they return EOF.
The printf Statement
The AWK versions of the printf statement and sprintf() function (see
below) accept the following conversion specification formats:
%c An ASCII character. If the argument used for %c is numeric, it
is treated as a character and printed. Otherwise, the argument
is assumed to be a string, and the only first character of that
string is printed.
%d, %i A decimal number (the integer part).
%e, %E A floating point number of the form [-]d.dddddde[+-]dd. The %E
format uses E instead of e.
%f, %F A floating point number of the form [-]ddd.dddddd. If the sys-
tem library supports it, %F is available as well. This is like
%f, but uses capital letters for special “not a number” and
“infinity” values. If %F is not available, gawk uses %f.
%g, %G Use %e or %f conversion, whichever is shorter, with nonsignifi-
cant zeros suppressed. The %G format uses %E instead of %e.
%o An unsigned octal number (also an integer).
%u An unsigned decimal number (again, an integer).
%s A character string.
%x, %X An unsigned hexadecimal number (an integer). The %X format
uses ABCDEF instead of abcdef.
%% A single % character; no argument is converted.
NOTE: When using the integer format-control letters for values that are
outside the range of a C long integer, gawk switches to the %0f format
specifier. If --lint is provided on the command line gawk warns about
this. Other versions of awk may print invalid values or do something
else entirely.
Optional, additional parameters may lie between the % and the control
letter:
count$ Use the count’th argument at this point in the formatting. This
is called a positional specifier and is intended primarily for
use in translated versions of format strings, not in the origi-
nal text of an AWK program. It is a gawk extension.
- The expression should be left-justified within its field.
space For numeric conversions, prefix positive values with a space,
and negative values with a minus sign.
+ The plus sign, used before the width modifier (see below), says
to always supply a sign for numeric conversions, even if the
data to be formatted is positive. The + overrides the space
modifier.
# Use an “alternate form” for certain control letters. For %o,
supply a leading zero. For %x, and %X, supply a leading 0x or
0X for a nonzero result. For %e, %E, %f and %F, the result
always contains a decimal point. For %g, and %G, trailing zeros
are not removed from the result.
0 A leading 0 (zero) acts as a flag, that indicates output should
be padded with zeroes instead of spaces. This applies even to
non-numeric output formats. This flag only has an effect when
the field width is wider than the value to be printed.
width The field should be padded to this width. The field is normally
padded with spaces. If the 0 flag has been used, it is padded
with zeroes.
.prec A number that specifies the precision to use when printing. For
the %e, %E, %f and %F, formats, this specifies the number of
digits you want printed to the right of the decimal point. For
the %g, and %G formats, it specifies the maximum number of sig-
nificant digits. For the %d, %o, %i, %u, %x, and %X formats, it
specifies the minimum number of digits to print. For %s, it
specifies the maximum number of characters from the string that
should be printed.
The dynamic width and prec capabilities of the ANSI C printf() routines
are supported. A * in place of either the width or prec specifications
causes their values to be taken from the argument list to printf or
sprintf(). To use a positional specifier with a dynamic width or pre-
cision, supply the count$ after the * in the format string. For exam-
ple, "%3$*2$.*1$s".
Special File Names
When doing I/O redirection from either print or printf into a file, or
via getline from a file, gawk recognizes certain special filenames
internally. These filenames allow access to open file descriptors
inherited from gawk’s parent process (usually the shell). These file
names may also be used on the command line to name data files. The
filenames are:
/dev/stdin The standard input.
/dev/stdout The standard output.
/dev/stderr The standard error output.
/dev/fd/n The file associated with the open file descriptor n.
These are particularly useful for error messages. For example:
print "You blew it!" > "/dev/stderr"
whereas you would otherwise have to use
print "You blew it!" | "cat 1>&2"
The following special filenames may be used with the |& co-process
operator for creating TCP/IP network connections.
/inet/tcp/lport/rhost/rport File for TCP/IP connection on local port
lport to remote host rhost on remote port
rport. Use a port of 0 to have the system
pick a port.
/inet/udp/lport/rhost/rport Similar, but use UDP/IP instead of TCP/IP.
/inet/raw/lport/rhost/rport Reserved for future use.
Other special filenames provide access to information about the running
gawk process. These filenames are now obsolete. Use the PROCINFO
array to obtain the information they provide. The filenames are:
/dev/pid Reading this file returns the process ID of the current
process, in decimal, terminated with a newline.
/dev/ppid Reading this file returns the parent process ID of the cur-
rent process, in decimal, terminated with a newline.
/dev/pgrpid Reading this file returns the process group ID of the cur-
rent process, in decimal, terminated with a newline.
/dev/user Reading this file returns a single record terminated with a
newline. The fields are separated with spaces. $1 is the
value of the getuid(2) system call, $2 is the value of the
geteuid(2) system call, $3 is the value of the getgid(2)
system call, and $4 is the value of the getegid(2) system
call. If there are any additional fields, they are the
group IDs returned by getgroups(2). Multiple groups may
not be supported on all systems.
Numeric Functions
AWK has the following built-in arithmetic functions:
atan2(y, x) Returns the arctangent of y/x in radians.
cos(expr) Returns the cosine of expr, which is in radians.
exp(expr) The exponential function.
int(expr) Truncates to integer.
log(expr) The natural logarithm function.
rand() Returns a random number N, between 0 and 1, such that 0 ≤
N < 1.
sin(expr) Returns the sine of expr, which is in radians.
sqrt(expr) The square root function.
srand([expr]) Uses expr as a new seed for the random number generator.
If no expr is provided, the time of day is used. The
return value is the previous seed for the random number
generator.
String Functions
Gawk has the following built-in string functions:
asort(s [, d]) Returns the number of elements in the source
array s. The contents of s are sorted using
gawk’s normal rules for comparing values, and
the indices of the sorted values of s are
replaced with sequential integers starting with
1. If the optional destination array d is spec-
ified, then s is first duplicated into d, and
then d is sorted, leaving the indices of the
source array s unchanged.
asorti(s [, d]) Returns the number of elements in the source
array s. The behavior is the same as that of
asort(), except that the array indices are used
for sorting, not the array values. When done,
the array is indexed numerically, and the val-
ues are those of the original indices. The
original values are lost; thus provide a second
array if you wish to preserve the original.
gensub(r, s, h [, t]) Search the target string t for matches of the
regular expression r. If h is a string
beginning with g or G, then replace all matches
of r with s. Otherwise, h is a number indicat-
ing which match of r to replace. If t is not
supplied, $0 is used instead. Within the
replacement text s, the sequence \n, where n is
a digit from 1 to 9, may be used to indicate
just the text that matched the n’th parenthe-
sized subexpression. The sequence \0 repre-
sents the entire matched text, as does the
character &. Unlike sub() and gsub(), the mod-
ified string is returned as the result of the
function, and the original target string is not
changed.
gsub(r, s [, t]) For each substring matching the regular expres-
sion r in the string t, substitute the string
s, and return the number of substitutions. If
t is not supplied, use $0. An & in the
replacement text is replaced with the text that
was actually matched. Use \& to get a literal
&. (This must be typed as "\\&"; see GAWK:
Effective AWK Programming for a fuller discus-
sion of the rules for &’s and backslashes in
the replacement text of sub(), gsub(), and gen-
sub().)
index(s, t) Returns the index of the string t in the string
s, or 0 if t is not present. (This implies
that character indices start at one.)
length([s]) Returns the length of the string s, or the
length of $0 if s is not supplied. Starting
with version 3.1.5, as a non-standard exten-
sion, with an array argument, length() returns
the number of elements in the array.
match(s, r [, a]) Returns the position in s where the regular
expression r occurs, or 0 if r is not present,
and sets the values of RSTART and RLENGTH.
Note that the argument order is the same as for
the ~ operator: str ~ re. If array a is pro-
vided, a is cleared and then elements 1 through
n are filled with the portions of s that match
the corresponding parenthesized subexpression
in r. The 0’th element of a contains the por-
tion of s matched by the entire regular expres-
sion r. Subscripts a[n, "start"], and a[n,
"length"] provide the starting index in the
string and length respectively, of each match-
ing substring.
split(s, a [, r]) Splits the string s into the array a on the
regular expression r, and returns the number of
fields. If r is omitted, FS is used instead.
The array a is cleared first. Splitting
behaves identically to field splitting,
described above.
sprintf(fmt, expr-list) Prints expr-list according to fmt, and returns
the resulting string.
strtonum(str) Examines str, and returns its numeric value.
If str begins with a leading 0, strtonum()
assumes that str is an octal number. If str
begins with a leading 0x or 0X, strtonum()
assumes that str is a hexadecimal number.
sub(r, s [, t]) Just like gsub(), but only the first matching
substring is replaced.
substr(s, i [, n]) Returns the at most n-character substring of s
starting at i. If n is omitted, the rest of s
is used.
tolower(str) Returns a copy of the string str, with all the
upper-case characters in str translated to
their corresponding lower-case counterparts.
Non-alphabetic characters are left unchanged.
toupper(str) Returns a copy of the string str, with all the
lower-case characters in str translated to
their corresponding upper-case counterparts.
Non-alphabetic characters are left unchanged.
As of version 3.1.5, gawk is multibyte aware. This means that index(),
length(), substr() and match() all work in terms of characters, not
bytes.
Time Functions
Since one of the primary uses of AWK programs is processing log files
that contain time stamp information, gawk provides the following func-
tions for obtaining time stamps and formatting them.
mktime(datespec)
Turns datespec into a time stamp of the same form as returned
by systime(). The datespec is a string of the form YYYY MM
DD HH MM SS[ DST]. The contents of the string are six or
seven numbers representing respectively the full year includ-
ing century, the month from 1 to 12, the day of the month
from 1 to 31, the hour of the day from 0 to 23, the minute
from 0 to 59, and the second from 0 to 60, and an optional
daylight saving flag. The values of these numbers need not
be within the ranges specified; for example, an hour of -1
means 1 hour before midnight. The origin-zero Gregorian cal-
endar is assumed, with year 0 preceding year 1 and year -1
preceding year 0. The time is assumed to be in the local
timezone. If the daylight saving flag is positive, the time
is assumed to be daylight saving time; if zero, the time is
assumed to be standard time; and if negative (the default),
mktime() attempts to determine whether daylight saving time
is in effect for the specified time. If datespec does not
contain enough elements or if the resulting time is out of
range, mktime() returns -1.
strftime([format [, timestamp[, utc-flag]]])
Formats timestamp according to the specification in format.
If utc-flag is present and is non-zero or non-null, the
result is in UTC, otherwise the result is in local time. The
timestamp should be of the same form as returned by sys-
time(). If timestamp is missing, the current time of day is
used. If format is missing, a default format equivalent to
the output of date(1) is used. See the specification for the
strftime() function in ANSI C for the format conversions that
are guaranteed to be available.
systime() Returns the current time of day as the number of seconds
since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems).
Bit Manipulations Functions
Starting with version 3.1 of gawk, the following bit manipulation func-
tions are available. They work by converting double-precision floating
point values to uintmax_t integers, doing the operation, and then con-
verting the result back to floating point. The functions are:
and(v1, v2) Return the bitwise AND of the values provided by v1
and v2.
compl(val) Return the bitwise complement of val.
lshift(val, count) Return the value of val, shifted left by count
bits.
or(v1, v2) Return the bitwise OR of the values provided by v1
and v2.
rshift(val, count) Return the value of val, shifted right by count
bits.
xor(v1, v2) Return the bitwise XOR of the values provided by v1
and v2.
Internationalization Functions
Starting with version 3.1 of gawk, the following functions may be used
from within your AWK program for translating strings at run-time. For
full details, see GAWK: Effective AWK Programming.
bindtextdomain(directory [, domain])
Specifies the directory where gawk looks for the .mo files, in
case they will not or cannot be placed in the ‘‘standard’’ loca-
tions (e.g., during testing). It returns the directory where
domain is ‘‘bound.’’
The default domain is the value of TEXTDOMAIN. If directory is
the null string (""), then bindtextdomain() returns the current
binding for the given domain.
dcgettext(string [, domain [, category]])
Returns the translation of string in text domain domain for
locale category category. The default value for domain is the
current value of TEXTDOMAIN. The default value for category is
"LC_MESSAGES".
If you supply a value for category, it must be a string equal to
one of the known locale categories described in GAWK: Effective
AWK Programming. You must also supply a text domain. Use
TEXTDOMAIN if you want to use the current domain.
dcngettext(string1 , string2 , number [, domain [, category]])
Returns the plural form used for number of the translation of
string1 and string2 in text domain domain for locale category
category. The default value for domain is the current value of
TEXTDOMAIN. The default value for category is "LC_MESSAGES".
If you supply a value for category, it must be a string equal to
one of the known locale categories described in GAWK: Effective
AWK Programming. You must also supply a text domain. Use
TEXTDOMAIN if you want to use the current domain.
USER-DEFINED FUNCTIONS
Functions in AWK are defined as follows:
function name(parameter list) { statements }
Functions are executed when they are called from within expressions in
either patterns or actions. Actual parameters supplied in the function
call are used to instantiate the formal parameters declared in the
function. Arrays are passed by reference, other variables are passed
by value.
Since functions were not originally part of the AWK language, the pro-
vision for local variables is rather clumsy: They are declared as extra
parameters in the parameter list. The convention is to separate local
variables from real parameters by extra spaces in the parameter list.
For example:
function f(p, q, a, b) # a and b are local
{
...
}
/abc/ { ... ; f(1, 2) ; ... }
The left parenthesis in a function call is required to immediately fol-
low the function name, without any intervening white space. This
avoids a syntactic ambiguity with the concatenation operator. This
restriction does not apply to the built-in functions listed above.
Functions may call each other and may be recursive. Function parame-
ters used as local variables are initialized to the null string and the
number zero upon function invocation.
Use return expr to return a value from a function. The return value is
undefined if no value is provided, or if the function returns by
“falling off” the end.
If --lint has been provided, gawk warns about calls to undefined func-
tions at parse time, instead of at run time. Calling an undefined
function at run time is a fatal error.
The word func may be used in place of function.
DYNAMICALLY LOADING NEW FUNCTIONS
Beginning with version 3.1 of gawk, you can dynamically add new built-
in functions to the running gawk interpreter. The full details are
beyond the scope of this manual page; see GAWK: Effective AWK Program-
ming for the details.
extension(object, function)
Dynamically link the shared object file named by object, and
invoke function in that object, to perform initialization.
These should both be provided as strings. Returns the value
returned by function.
This function is provided and documented in GAWK: Effective AWK Pro-
gramming, but everything about this feature is likely to change eventu-
ally. We STRONGLY recommend that you do not use this feature for any-
thing that you aren’t willing to redo.
SIGNALS
pgawk accepts two signals. SIGUSR1 causes it to dump a profile and
function call stack to the profile file, which is either awkprof.out,
or whatever file was named with the --profile option. It then contin-
ues to run. SIGHUP causes pgawk to dump the profile and function call
stack and then exit.
EXAMPLES
Print and sort the login names of all users:
BEGIN { FS = ":" }
{ print $1 | "sort" }
Count lines in a file:
{ nlines++ }
END { print nlines }
Precede each line by its number in the file:
{ print FNR, $0 }
Concatenate and line number (a variation on a theme):
{ print NR, $0 }
Run an external command for particular lines of data:
tail -f access_log |
awk ’/myhome.html/ { system("nmap " $1 ">> logdir/myhome.html") }’
INTERNATIONALIZATION
String constants are sequences of characters enclosed in double quotes.
In non-English speaking environments, it is possible to mark strings in
the AWK program as requiring translation to the native natural lan-
guage. Such strings are marked in the AWK program with a leading under-
score (“_”). For example,
gawk ’BEGIN { print "hello, world" }’
always prints hello, world. But,
gawk ’BEGIN { print _"hello, world" }’
might print bonjour, monde in France.
There are several steps involved in producing and running a localizable
AWK program.
1. Add a BEGIN action to assign a value to the TEXTDOMAIN variable to
set the text domain to a name associated with your program.
BEGIN { TEXTDOMAIN = "myprog" }
This allows gawk to find the .mo file associated with your program.
Without this step, gawk uses the messages text domain, which likely
does not contain translations for your program.
2. Mark all strings that should be translated with leading under-
scores.
3. If necessary, use the dcgettext() and/or bindtextdomain() functions
in your program, as appropriate.
4. Run gawk --gen-po -f myprog.awk > myprog.po to generate a .po file
for your program.
5. Provide appropriate translations, and build and install the corre-
sponding .mo files.
The internationalization features are described in full detail in GAWK:
Effective AWK Programming.
POSIX COMPATIBILITY
A primary goal for gawk is compatibility with the POSIX standard, as
well as with the latest version of UNIX awk. To this end, gawk incor-
porates the following user visible features which are not described in
the AWK book, but are part of the Bell Laboratories version of awk, and
are in the POSIX standard.
The book indicates that command line variable assignment happens when
awk would otherwise open the argument as a file, which is after the
BEGIN block is executed. However, in earlier implementations, when
such an assignment appeared before any file names, the assignment would
happen before the BEGIN block was run. Applications came to depend on
this “feature.” When awk was changed to match its documentation, the
-v option for assigning variables before program execution was added to
accommodate applications that depended upon the old behavior. (This
feature was agreed upon by both the Bell Laboratories and the GNU
developers.)
The -W option for implementation specific features is from the POSIX
standard.
When processing arguments, gawk uses the special option “--” to signal
the end of arguments. In compatibility mode, it warns about but other-
wise ignores undefined options. In normal operation, such arguments
are passed on to the AWK program for it to process.
The AWK book does not define the return value of srand(). The POSIX
standard has it return the seed it was using, to allow keeping track of
random number sequences. Therefore srand() in gawk also returns its
current seed.
Other new features are: The use of multiple -f options (from MKS awk);
the ENVIRON array; the \a, and \v escape sequences (done originally in
gawk and fed back into the Bell Laboratories version); the tolower()
and toupper() built-in functions (from the Bell Laboratories version);
and the ANSI C conversion specifications in printf (done first in the
Bell Laboratories version).
HISTORICAL FEATURES
There are two features of historical AWK implementations that gawk sup-
ports. First, it is possible to call the length() built-in function
not only with no argument, but even without parentheses! Thus,
a = length # Holy Algol 60, Batman!
is the same as either of
a = length()
a = length($0)
This feature is marked as “deprecated” in the POSIX standard, and gawk
issues a warning about its use if --lint is specified on the command
line.
The other feature is the use of either the continue or the break state-
ments outside the body of a while, for, or do loop. Traditional AWK
implementations have treated such usage as equivalent to the next
statement. Gawk supports this usage if --traditional has been speci-
fied.
GNU EXTENSIONS
Gawk has a number of extensions to POSIX awk. They are described in
this section. All the extensions described here can be disabled by
invoking gawk with the --traditional or --posix options.
The following features of gawk are not available in POSIX awk.
· No path search is performed for files named via the -f option.
Therefore the AWKPATH environment variable is not special.
· The \x escape sequence. (Disabled with --posix.)
· The fflush() function. (Disabled with --posix.)
· The ability to continue lines after ? and :. (Disabled with
--posix.)
· Octal and hexadecimal constants in AWK programs.
· The ARGIND, BINMODE, ERRNO, LINT, RT and TEXTDOMAIN variables are not
special.
· The IGNORECASE variable and its side-effects are not available.
· The FIELDWIDTHS variable and fixed-width field splitting.
· The PROCINFO array is not available.
· The use of RS as a regular expression.
· The special file names available for I/O redirection are not recog-
nized.
· The |& operator for creating co-processes.
· The ability to split out individual characters using the null string
as the value of FS, and as the third argument to split().
· The optional second argument to the close() function.
· The optional third argument to the match() function.
· The ability to use positional specifiers with printf and sprintf().
· The ability to pass an array to length().
· The use of delete array to delete the entire contents of an array.
· The use of nextfile to abandon processing of the current input file.
· The and(), asort(), asorti(), bindtextdomain(), compl(), dcgettext(),
dcngettext(), gensub(), lshift(), mktime(), or(), rshift(), strf-
time(), strtonum(), systime() and xor() functions.
· Localizable strings.
· Adding new built-in functions dynamically with the extension() func-
tion.
The AWK book does not define the return value of the close() function.
Gawk’s close() returns the value from fclose(3), or pclose(3), when
closing an output file or pipe, respectively. It returns the process’s
exit status when closing an input pipe. The return value is -1 if the
named file, pipe or co-process was not opened with a redirection.
When gawk is invoked with the --traditional option, if the fs argument
to the -F option is “t”, then FS is set to the tab character. Note
that typing gawk -F\t ... simply causes the shell to quote the “t,”
and does not pass “\t” to the -F option. Since this is a rather ugly
special case, it is not the default behavior. This behavior also does
not occur if --posix has been specified. To really get a tab character
as the field separator, it is best to use single quotes: gawk -F’\t’
....
If gawk is configured with the --enable-switch option to the configure
command, then it accepts an additional control-flow statement:
switch (expression) {
case value|regex : statement
...
[ default: statement ]
}
If gawk is configured with the --disable-directories-fatal option, then
it will silently skip directories named on the command line. Other-
wise, it will do so only if invoked with the --traditional option.
ENVIRONMENT VARIABLES
The AWKPATH environment variable can be used to provide a list of
directories that gawk searches when looking for files named via the -f
and --file options.
If POSIXLY_CORRECT exists in the environment, then gawk behaves exactly
as if --posix had been specified on the command line. If --lint has
been specified, gawk issues a warning message to this effect.
SEE ALSO
egrep(1), getpid(2), getppid(2), getpgrp(2), getuid(2), geteuid(2),
getgid(2), getegid(2), getgroups(2)
The AWK Programming Language, Alfred V. Aho, Brian W. Kernighan, Peter
J. Weinberger, Addison-Wesley, 1988. ISBN 0-201-07981-X.
GAWK: Effective AWK Programming, Edition 3.0, published by the Free
Software Foundation, 2001. The current version of this document is
available online at http://www.gnu.org/software/gawk/manual.
BUGS
The -F option is not necessary given the command line variable assign-
ment feature; it remains only for backwards compatibility.
Syntactically invalid single character programs tend to overflow the
parse stack, generating a rather unhelpful message. Such programs are
surprisingly difficult to diagnose in the completely general case, and
the effort to do so really is not worth it.
AUTHORS
The original version of UNIX awk was designed and implemented by Alfred
Aho, Peter Weinberger, and Brian Kernighan of Bell Laboratories. Brian
Kernighan continues to maintain and enhance it.
Paul Rubin and Jay Fenlason, of the Free Software Foundation, wrote
gawk, to be compatible with the original version of awk distributed in
Seventh Edition UNIX. John Woods contributed a number of bug fixes.
David Trueman, with contributions from Arnold Robbins, made gawk com-
patible with the new version of UNIX awk. Arnold Robbins is the cur-
rent maintainer.
The initial DOS port was done by Conrad Kwok and Scott Garfinkle.
Scott Deifik is the current DOS maintainer. Pat Rankin did the port to
VMS, and Michal Jaegermann did the port to the Atari ST. The port to
OS/2 was done by Kai Uwe Rommel, with contributions and help from
Darrel Hankerson. Andreas Buening now maintains the OS/2 port. Fred
Fish supplied support for the Amiga, and Martin Brown provided the BeOS
port. Stephen Davies provided the original Tandem port, and Matthew
Woehlke provided changes for Tandem’s POSIX-compliant systems. Ralf
Wildenhues now maintains that port.
See the README file in the gawk distribution for current information
about maintainers and which ports are currently supported.
VERSION INFORMATION
This man page documents gawk, version 3.1.7.
BUG REPORTS
If you find a bug in gawk, please send electronic mail to bug-
gawk@gnu.org. Please include your operating system and its revision,
the version of gawk (from gawk --version), what C compiler you used to
compile it, and a test program and data that are as small as possible
for reproducing the problem.
Before sending a bug report, please do the following things. First,
verify that you have the latest version of gawk. Many bugs (usually
subtle ones) are fixed at each release, and if yours is out of date,
the problem may already have been solved. Second, please see if set-
ting the environment variable LC_ALL to LC_ALL=C causes things to
behave as you expect. If so, it’s a locale issue, and may or may not
really be a bug. Finally, please read this man page and the reference
manual carefully to be sure that what you think is a bug really is,
instead of just a quirk in the language.
Whatever you do, do NOT post a bug report in comp.lang.awk. While the
gawk developers occasionally read this newsgroup, posting bug reports
there is an unreliable way to report bugs. Instead, please use the
electronic mail addresses given above.
If you’re using a GNU/Linux system or BSD-based system, you may wish to
submit a bug report to the vendor of your distribution. That’s fine,
but please send a copy to the official email address as well, since
there’s no guarantee that the bug will be forwarded to the gawk main-
tainer.
ACKNOWLEDGEMENTS
Brian Kernighan of Bell Laboratories provided valuable assistance dur-
ing testing and debugging. We thank him.
COPYING PERMISSIONS
Copyright © 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2001, 2002, 2003, 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
Permission is granted to make and distribute verbatim copies of this
manual page provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual page under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
Permission is granted to copy and distribute translations of this man-
ual page into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a trans-
lation approved by the Foundation.
Free Software Foundation Jul 10 2009 GAWK(1)