Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

sortのオプションを使えば自然な形で整列してくれる。

以下のような文字列があったとします。

$ seq -10 10 | sed -e s/^4/hoge/ -e s/^-8/fuga/
-10
-9
fuga
-7
-6
-5
-4
-3
-2
-1
0
1
2
3
hoge
5
6
7
8
9
10

デフォルトのsortだと、

$ seq -10 10 | sed -e s/^4/hoge/ -e s/^-8/fuga/ 
-1
-10
-2
-3
-4
-5
-6
-7
-9
0
1
10
2
3
5
6
7
8
9
fuga
hoge

と使い勝手が悪いです。

オプションをつかう

'-n'

  • nオプションを使うと、マイナス=>ゼロ=>文字列=>プラスの順に整列してくれます。
$ seq -10 10 | sed -e s/^4/hoge/ -e s/^-8/fuga/ | sort -n
-10
-9
-7
-6
-5
-4
-3
-2
-1
0
fuga
hoge
1
2
3
5
6
7
8
9
10

'-g'

更に過激なオプションとして、-gもあります。
これは 文字列 =>マイナス => ゼロ => プラスの順に並べてくれます。

$ seq -10 10 | sed -e s/^4/hoge/ -e s/^-8/fuga/ | sort -g
fuga
hoge
-10
-9
-7
-6
-5
-4
-3
-2
-1
0
1
2
3
5
6
7
8
9
10

これは速度面等々から推奨されない方式のようです

'-g'
'--general-numeric-sort'
'--sort=general-numeric'
Sort numerically, converting a prefix of each line to a long
double-precision floating point number. *Note Floating point::.
Do not report overflow, underflow, or conversion errors. Use the
following collating sequence:

* Lines that do not start with numbers (all considered to be
equal).
* NaNs ("Not a Number" values, in IEEE floating point
arithmetic) in a consistent but machine-dependent order.
* Minus infinity.
* Finite numbers in ascending numeric order (with -0 and +0
equal).
* Plus infinity.

Use this option only if there is no alternative; it is much slower
than '--numeric-sort' ('-n') and it can lose information when
converting to floating point.

オプションなど使わないで済むなら、それに越した事はありません。
使わないで済むように、先方様とはよーくデータ型の打ち合わせをして下さいね(白目

参考もと

  • man sort