head by awk2010年11月21日 06時41分50秒

head を awk で実装するには条件式{式}条件式のみの省略がそのまま当てはまる。head は何も引数を与えられない時には先頭十行を出力する。

% head /etc/defaults/rc.conf
#!/bin/sh

# This is rc.conf - a file full of useful variables that you can set
# to change the default startup behavior of your system.  You should
# not edit this file!  Put any overrides into one of the ${rc_conf_files}
# instead and you will be able to update these defaults later without
# spamming your local configuration information.
#
# The ${rc_conf_files} files should only contain values which override
# values set in this file.  This eases the upgrade path when defaults
% awk 'NR <= 10' /etc/defaults/rc.conf
#!/bin/sh

# This is rc.conf - a file full of useful variables that you can set
# to change the default startup behavior of your system.  You should
# not edit this file!  Put any overrides into one of the ${rc_conf_files}
# instead and you will be able to update these defaults later without
# spamming your local configuration information.
#
# The ${rc_conf_files} files should only contain values which override
# values set in this file.  This eases the upgrade path when defaults
%

これはこれで動作するのだが、巨大なファイルが入力の場合は、捨てるだけの入力を延々と読み込み続けることになる。そこで、出力が終わり次第、プログラムを終了させれば余計な読み込みを避けられる。


% nawk '{print; if(NR >= 10) exit 0}' /etc/defaults/rc.conf
#!/bin/sh

# This is rc.conf - a file full of useful variables that you can set
# to change the default startup behavior of your system.  You should
# not edit this file!  Put any overrides into one of the ${rc_conf_files}
# instead and you will be able to update these defaults later without
# spamming your local configuration information.
#
# The ${rc_conf_files} files should only contain values which override
# values set in this file.  This eases the upgrade path when defaults
%

awk でも他の言語と同様に if 文がある。そこで、NR 変数を調べて、十行目を読み次第終了する。exit関数は即座に awk を終了させる。引数を渡さないと 0 が返る。引数で任意の値を返してもいい。

print 文で入力行をそのまま出力している。ここでは二つ以上の式が一行に並ぶために、セミコロンで式を区切っている。awk の式の区切りは、改行かセミコロンで行なわれる。

今回の要点。

  1. if 条件式
  2. exit 関数
  3. 式の区切りは改行かセミコロン
  4. NR

コメント

コメントをどうぞ

※メールアドレスとURLの入力は必須ではありません。 入力されたメールアドレスは記事に反映されず、ブログの管理者のみが参照できます。

※なお、送られたコメントはブログの管理者が確認するまで公開されません。

名前:
メールアドレス:
URL:
コメント:

トラックバック

このエントリのトラックバックURL: http://uyota.asablo.jp/blog/2010/11/21/5522501/tb

※なお、送られたトラックバックはブログの管理者が確認するまで公開されません。