(O+P)ut

アウトプット



(O+P)ut

エンジニアのアウトプット

【Linux】numutilsでワンライナーを省力化する

スポンサーリンク

Debian GNU/Linux 9にてスクリプトやコマンドを利用して数値演算をすることがありますが、例えば数値列の合計値を算出する場合は以下で可能です。

$ seq 1 5
1
2
3
4
5
$ seq 1 5 | awk '{a+=$1} END{print a;}'
15

しかし、数値を合計するという処理に特化したnumsumを使えば

$ seq 1 5 | numsum
15

スッキリした記載にできます。本記事では他にも便利なコマンドを紹介します。

numutilsをインストール

デフォルトではnumsumコマンドは入っていないので

$ which numsum

以下でパッケージを確認して

$ apt-cache search numsum
num-utils - programs for dealing with numbers from the command line

apt-getでインストールしました。

$ apt-get install num-utils
...
The following packages were automatically installed and are no longer required:
  libx11-6 libx11-data libxau6 libxcb1 libxdmcp6
...

インストールできています。

$ which numsum
/usr/bin/numsum

利用方法

パッケージの中身は以下です。

$ apt-cache show num-utils
...
Includes these programs:
  * numaverage: A program for calculating the average of numbers.
  * numbound: Finds the boundary numbers (min and max) of input.
  * numinterval: Shows the numeric intervals between each number in a sequence.
  * numnormalize: Normalizes a set of numbers between 0 and 1 by default.
  * numgrep: Like normal grep, but for sets of numbers.
  * numprocess: Do mathematical operations on numbers.
  * numsum: Add up all the numbers.
  * numrandom: Generate a random number from a given expression.
  * numrange: Generate a set of numbers in a range expression.
  * numround: Round each number according to its value.

一通り試しましたが以下は使う場面が思いついたので覚えておこうと思います。

平均値を求める

以下は平均値です。

$ cat pi.txt
3
1
4
1
5
9
2
$ cat pi.txt | numaverage
3.57142857142857

最頻値を求める

$ cat pi.txt | numaverage -m
1

中央値を求める

$ cat pi.txt | numaverage -M
3

1 1 2 3 4 5 9

の中央値は確かに「3」です。

ここで「6」を追加すると

$ cat pi2.txt
3
1
4
1
5
9
2
6
$ cat pi2.txt | numaverage -M
4

「3」と「4」の間ではなく「4」と出力されたので偶数におけるこの動きは覚えておいた方がよさそうです。

合計値を求める

冒頭のnumsumです。

$ cat pi2.txt | numsum
31

最大値を求める

$ cat pi2.txt | numbound
9

終わりに

awkやsedを用いて数値や文字列処理をするのが一般的ですが、よく使う処理に関してはこれらのコマンド群を利用するのも手だと思ったので紹介しました。

ご参考になれば幸いです。