LoginSignup
1
3

More than 5 years have passed since last update.

[awk] 自作関数の定義と利用

Posted at

自作関数の定義

awkでユーザー定義関数である自作関数を導入するには次のように書きます。

awk 'function function_name(x, y, z, ...) {
    関数の中身
}'

これは、引数x, y, z, ...をとり、関数名はfunction_nameということを意味しています。

底が10のlog10()関数を定義してみます。(awkにはデフォルトで自然対数のlog()関数しか用意されていません。)

awk 'function log10(x) {
    return log(x)/log(10);
}
{
    print log10($1);
}' test.txt

入力されたtest.txtの1列目のデータに対して常用対数値を計算し出力します。

入力データ例

1
10
100
1000
10000
100000

出力結果

0
1
2
3
4
5
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3