例えば以下のような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コマンドでファイルの中身を並び替えする方法をご紹介