I wanted to put a line number at the beginning of a CSV file that has hundreds of lines. I was wondering if there was any good way, and I don't want to use Excel because unexpected things happen when I process CSV files with Excel. Would you like to write it in a shell? The method I found when I thought it was troublesome.
--Environment --Windows10 64bit version 1909 - nl (GNU coreutils) 8.31
How to put a line number at the beginning of a CSV file
$ nl -w1 -s, {Original CSV}.csv > {CSV with line numbers}.csv
The nl command displays the file with line numbers.
$ 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"
Minimize the line number display width with the -W1 option.
#I got angry when I specified "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"
The -s, option displays "," after the line number.
$ 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] Command-Output a text file with line numbers: Linux basic command Tips (98)-@IT](https://www.atmarkit.co.jp/ait/articles/1703/30/news024 .html)
Recommended Posts