sort
テキスト処理
書き方
sort -k 2 -n [file]行を並べ替えます。-n が無いと文字として比べるので 10 が 9 より前に来て、順序はロケールが決めるため LC_ALL=C を前に置くと固定できます。
よく使うオプション
| オプション | 意味 |
|---|---|
| -n | Compare as numbers, not as text |
| -h | Compare human sizes such as 2K and 1G |
| -r | Reverse the order |
| -k | Sort by a field, as in -k2 |
| -t | Set the field separator |
| -u | Drop duplicate lines |
| -f | Ignore case |
| -o | Write the result to a file, even back onto the input |
例
du -sh * | sort -hBiggest directory last.
sort -t, -k2 -n data.csvNumeric sort on the second column.
sort -u names.txtSorted, with duplicates gone.
パイプでつないで使うのが本来の形です。ひとつで全部やるより、三つつないだ方が短くなります。
読み方
- 角括弧 [ ] は省いてよい部分です。
- 三点 … は複数並べられるという意味です。
- オプションは大文字小文字を区別します — -r と -R が別物のコマンドもあります。
よくある質問
Q. sort は何をしますか。
行を並べ替えます。-n が無いと文字として比べるので 10 が 9 より前に来て、順序はロケールが決めるため LC_ALL=C を前に置くと固定できます。
Q. どう打ちますか。
sort -k 2 -n [file] — 角括弧は省いてよい部分です。
Q. よく使うオプションはいくつですか。
ここにまとめたのは8個です。全部は man sort にあります。このコマンドはテキスト処理の仲間です。
関連するコマンド
man ページ: man sort