LoginSignup
1
1

More than 3 years have passed since last update.

CSVファイルの行頭に行番号を入れる方法

Posted at

行数が数百行あるCSVファイルの行頭に行番号を入れたかった。
何かいい方法はないかと悩んだ、ExcelでCSVファイルを加工すると思わぬことが起こるのでExcelは使いたくない。
shellでも書くか・・・面倒くさい、と思った時に見つけた方法。

  • 環境
    • Windows10 64bit バージョン1909
    • nl (GNU coreutils) 8.31
CSVファイルの行頭に行番号を入れる方法
$ nl -w1 -s, {元のCSV}.csv > {行番号付きCSV}.csv

nlコマンドは行番号付きでファイルを表示してくれる。

$ nl sample.csv
     1  "hoge",2020/05/31,"fuga"
     2  "kuma",2020/05/30,"usagi"
     3  "tako",2020/05/29,"inu"
     4  "ponsuke",2020/05/02,"numa"

-W1オプションで行番号の表示幅を最小にする。

# 「0」を指定したら怒られた
$ nl -w0 sample.csv
nl: invalid line number field width: ‘0’: Numerical result out of range

$ nl -w1 sample.csv
1       "hoge",2020/05/31,"fuga"
2       "kuma",2020/05/30,"usagi"
3       "tako",2020/05/29,"inu"
4       "ponsuke",2020/05/02,"numa"

-s,オプションで行番号の後に「,」を表示してくれる。

$ nl -w1 -s, sample.csv
1,"hoge",2020/05/31,"fuga"
2,"kuma",2020/05/30,"usagi"
3,"tako",2020/05/29,"inu"
4,"ponsuke",2020/05/02,"numa"

参考

【 nl 】コマンド――テキストファイルを行番号付きで出力する:Linux基本コマンドTips(98) - @IT

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