-2

I am really struggling to add a new column with the line number in the terminal to a pipe delimited file

My current file looks like this:

ID|FirstName|LastName
12|John|Svernson
23|Mark|Wright
11|Chris|Watson

And I want the file to look like the following:

LN|ID|FirstName|LastName
1|12|John|Svernson
2|23|Mark|Wright
3|11|Chris|Watson

I have over 90k lines. I couldn't find a way to do this. Any help or guidance would be appreciated. Thanks

Nant
  • 569
  • 2
  • 10
  • 24

4 Answers4

4

A fun alternative:

{ echo LN; seq $(( $(wc -l < file) - 1 )); } | paste -d'|' - file

although in reality I'd use

awk '{print (NR==1 ? "LN" : NR-1), $0}' OFS="|" file
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

could you please try following.

awk 'FNR==1{print "LN|"$0;next} {$1=++count "|" $1} 1'   Input_file

To write output into Input_file itself append > temp_file && mv temp_file Input_file in above code too.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

Use awk variable NR (record number):

awk -F'|' 'NR==1{print "LN" FS $0}NR!=1{print NR-1 FS $0}' file
Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
  • thanks for this but this doesn't actually write this in the file right? It's just prints it out? Is there a way to save this in the file? – Nant Oct 12 '18 at 15:18
  • 1
    @Nant https://stackoverflow.com/questions/16529716/awk-save-modifications-in-place – Corentin Limier Oct 12 '18 at 15:19
0

I would use nl. You may run into issues if your line number goes over 6 digits, but you can add a -w to increase the number width if you need to:

   { read line; echo "LN|$line"; cat | nl -w 10 -ba -s \|; } < input | 
       sed 's/^ *//';
William Pursell
  • 204,365
  • 48
  • 270
  • 300