1

i would to know how can i edit my csv file to add first column with name 'linenumber' and iterate through each line and insert the number of the line in this column ?

Something like that

TEST TEST2 TEST3
valu value value

To that

linenumber TEST TEST2 TEST3
1          valu value value

Thanks in advance

Stoufiler

Stoufiler
  • 175
  • 1
  • 2
  • 13

2 Answers2

1

Following awk should help you on same.

awk 'FNR==1{print "linenumber",$0;next} {print FNR-1,$0}'   Input_file

In case you need to edit the Input_file itself then following may help you.

awk 'FNR==1{print "linenumber",$0;next} {print FNR-1,$0}'  OFS=","  Input_file > temp_file && mv temp_file  Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • it's work well but it's not a new column in fact they add the number and the valu :/ – Stoufiler Oct 23 '17 at 12:33
  • @Stoufiler, could you please explain your statement above, sorry didn't get it. – RavinderSingh13 Oct 23 '17 at 12:35
  • sorry i'm not english :) the problem is now the file contain the same number of column but the first one is concatenate so the title of the first column is `linenumber TEST` and no `linenumber | TEST` – Stoufiler Oct 23 '17 at 12:35
  • @RavinderSingth13 Thanks, I'm going to try to explain myself correctly, Actually when I use the command you passed me the file is well modified but the linenumer column is not added, it is added to the first one so that the first one column equals linenumber + titleofthenextcolumn – Stoufiler Oct 23 '17 at 12:43
  • @RavinderSingth13 It doesn't it make the same thing, i publish a codeshare for showing you y problem [link]https://codeshare.io/Gbw3xV – Stoufiler Oct 23 '17 at 12:49
  • when i use this command, `awk 'FNR==1{print "linenumber,",$0;next} {print FNR-1",",$0}' input.csv > output.csv` it works but i have a space between coma after linenumber and the next column, how can i fix that ? – Stoufiler Oct 23 '17 at 13:41
  • @Stoufiler You have to modify the description and state that you have a comma separated input file. – thanasisp Oct 23 '17 at 13:44
  • i modify like that `awk 'BEGIN{FS=","}FNR==1{print "linenumber,",$0;next} {print FNR-1",",$0}' input.csv > output.csv` and it doesn't work anymore – Stoufiler Oct 23 '17 at 13:46
  • You have to define the output delimiter as comma: `awk 'FNR==1{print "linenumber,"$0;next} {OFS=","; print FNR-1,$0}' input.csv` – thanasisp Oct 23 '17 at 13:47
1

i found the answer, it's that

awk 'FNR==1{print "linenumber,"$0;next} {print FNR-1,$0}' OFS="," input.csv > output.csv

thanks for all

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Stoufiler
  • 175
  • 1
  • 2
  • 13