How to insert a sequence number column inside a pipe delimited csv file using shell scripting?

Hi All,
I need a shell script which could insert a sequence number column inside a dat file(pipe delimited).
I have the dat file similar to the one as shown below..
|A|B|C||D|E
|F|G|H||I|J
|K|L|M||N|O
|P|Q|R||S|T

As shown above, the column 4 is currently blank and i need to insert sequence numbers into it, so that the new data file becomes as shown below.
|A|B|C|1|D|E
|F|G|H|2|I|J
|K|L|M|3|N|O
|P|Q|R|4|S|T

If the data file has 'n' rows the last row must have n as the sequence number.
Please help!!

Try:

awk -F\| -vOFS=\| '{$5=NR}1' file
1 Like
awk -F\| '$5=NR' OFS=\| file
1 Like

Thanks bartus11 :slight_smile: ..
Now i have one more complication in the above question...:o

I have the dat file similar to the one as shown below..(column 5 will have only 7 or 8 and all the 7's and 8's are grouped)
|A|B|C||7|E
|F|G|H||7|J
|K|L|M||8|O
|P|Q|R||8|T

As shown above, the column 4 is currently blank and i need to insert sequence numbers into it, also now the sequence number depends upon the column 5, ie if the column 5 = 7 then column 4 will have one set of sequence numbers, for column 5 = 8 then again the sequence should start from 1 so that the new data file becomes as shown below.

|A|B|C|1|7|E
|F|G|H|2|7|J
|K|L|M|1|8|O
|P|Q|R|2|8|T

awk 'BEGIN{FS=OFS="|"}{y=$6!=x?0:y;x=$6}$5=++y' file
1 Like

Thank you Danmero :slight_smile: