LoginSignup
2
1

More than 1 year has passed since last update.

sortコマンドでcsvファイルを降順ソートする

Posted at

例えば以下のようなcsvファイルがあったとする。
これの3行目以降を、3列目をキーにして降順ソートしたい。

test.csv
DATETIME, REPOSITORY_URL, SCORE, LEVEL, RESULT
---
2021/12/28_2:59:17, https://xxx, 58, 1, SUCCESS
2021/12/29_3:06:33, https://xxx, 54, 1, SUCCESS
2021/12/29_3:06:54, https://xxx, 0, 0, FAIL
2021/12/29_3:07:22, https://xxx, 52, 1, SUCCESS
2021/12/29_3:07:37, https://xxx, 0, 0, FAIL
2021/12/29_4:37:54, https://xxx, 53, 1, SUCCESS

まず、先頭2行目はソート対象ではないので、tail -n +3により3行目以降を対象にする。

$ FNAME="test.csv"
$ tail -n +3 ${FNAME}
2021/12/28_2:59:17, https://xxx, 58, 1, SUCCESS
2021/12/29_3:06:33, https://xxx, 54, 1, SUCCESS
2021/12/29_3:06:54, https://xxx, 0, 0, FAIL
2021/12/29_3:07:22, https://xxx, 52, 1, SUCCESS
2021/12/29_3:07:37, https://xxx, 0, 0, FAIL
2021/12/29_4:37:54, https://xxx, 53, 1, SUCCESS

sort -nr -t, -k3により、カンマ区切りでみた時の3列目を、数字扱いで降順ソートする。

$ FNAME="test.csv"
$ tail -n +3 ${FNAME} | sort -nr -t, -k3
2021/12/28_2:59:17, https://xxx, 58, 1, SUCCESS
2021/12/29_3:06:33, https://xxx, 54, 1, SUCCESS
2021/12/29_4:37:54, https://xxx, 53, 1, SUCCESS
2021/12/29_3:07:22, https://xxx, 52, 1, SUCCESS
2021/12/29_3:07:37, https://xxx, 0, 0, FAIL
2021/12/29_3:06:54, https://xxx, 0, 0, FAIL

その後、先頭2行目とくっつけて出力すればOK

$ FNAME="test.csv"
$ cat <(head -2 ${FNAME}) <(tail -n +3 ${FNAME} | sort -nr -t, -k3)
DATETIME, REPOSITORY_URL, SCORE, LEVEL, RESULT
---
2021/12/28_2:59:17, https://xxx, 58, 1, SUCCESS
2021/12/29_3:06:33, https://xxx, 54, 1, SUCCESS
2021/12/29_4:37:54, https://xxx, 53, 1, SUCCESS
2021/12/29_3:07:22, https://xxx, 52, 1, SUCCESS
2021/12/29_3:07:37, https://xxx, 0, 0, FAIL
2021/12/29_3:06:54, https://xxx, 0, 0, FAIL

columnを使うと見易くなる

$ FNAME="test.csv"
$ cat <(head -2 ${FNAME}) <(tail -n +3 ${FNAME} | sort -nr -t, -k3 | column -t -s,)
DATETIME, REPOSITORY_URL, SCORE, LEVEL, RESULT
---
2021/12/28_2:59:17   https://xxx   58   1   SUCCESS
2021/12/29_3:06:33   https://xxx   54   1   SUCCESS
2021/12/29_4:37:54   https://xxx   53   1   SUCCESS
2021/12/29_3:07:22   https://xxx   52   1   SUCCESS
2021/12/29_3:07:37   https://xxx   0    0   FAIL
2021/12/29_3:06:54   https://xxx   0    0   FAIL

参考

ファイルのn行目以降を表示する
sortコマンドでCSVファイルをソートする場合はソート列の指定方法に注意
sortコマンドとは?Linuxコマンドでファイルの中身を並び替えする方法をご紹介

2
1
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
2
1