[英]Add index column to CSV file
I have a large Comma-Separated File (6GB) and would like to add an index column to it.我有一个大的逗号分隔文件 (6GB),并想向其中添加一个索引列。 I'm looking at Unix type solutions for efficiency.
我正在寻找 Unix 类型的解决方案以提高效率。 I'm using a Mac.
我正在使用 Mac。
I have this:我有这个:
V1 V2 V3
0.4625 0.9179 0.8384
0.9324 0.2486 0.1114
0.6691 0.7813 0.6705
0.1935 0.3303 0.4336
Would like to get this:想得到这个:
ID V1 V2 V3
1 0.4625 0.9179 0.8384
2 0.9324 0.2486 0.1114
3 0.6691 0.7813 0.6705
4 0.1935 0.3303 0.4336
This will probably work:这可能会起作用:
awk -F'\t' -v OFS='\t' '
NR == 1 {print "ID", $0; next}
{print (NR-1), $0}
' input.csv > output.csv
In awk
, the NR
variable is "the total number of input records seen so far", which in general means "the current line number".在
awk
, NR
变量是“迄今为止看到的输入记录总数”,通常表示“当前行号”。 So the NR == 1
in the first line is how we match the first record and add the "ID" column header, and for the remaining lines we use NR-1
as the index.因此,第一行中的
NR == 1
是我们如何匹配第一条记录并添加“ID”列标题,对于其余行,我们使用NR-1
作为索引。
The -F'\\t'
argument sets the input field separator, and -vOFS='\\t'
sets the output field separator. -F'\\t'
参数设置输入字段分隔符, -vOFS='\\t'
设置输出字段分隔符。
Since no technology is specified in the original post, I'd be happy here to keep it simple.由于原始帖子中没有指定技术,我很乐意在这里保持简单。
(all the fancy Vim
/ bash
solutions are fine if you know what you're doing) . (如果您知道自己在做什么,那么所有花哨的
Vim
/ bash
解决方案都很好) 。
This last step will fill the index column with 1,2,3...
etc. You can then save the resulting spreadsheet as a CSV file again.最后一步将用
1,2,3...
等填充索引列。然后您可以再次将生成的电子表格另存为 CSV 文件。
I assume you have a commas delimited file.我假设你有一个逗号分隔的文件。
Using vim, open the file.使用 vim 打开文件。 In normal mode, type
在正常模式下,键入
:%s/^/\=line('.').','/
:%s/^/\\=line('.')/
adds the line number at the beginning of the line. :%s/^/\\=line('.')/
在行首添加行号。 Since you have a commas delimited file (add a column) you need a comma after your line number.由于您有一个逗号分隔的文件(添加一列),因此行号后需要一个逗号。 so the
.','
所以
.','
see this answer for full explanation about :%s/^/\\=line('.')/
有关
:%s/^/\\=line('.')/
完整解释,请参阅此答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.