How do I change the values to values I wanted line by line in a file?

Hi all,
I stored the result of network card information in a file as following picture.


The third row in the file is “SLOT NAME”, fourth row is “port index”.
I want to use the same SLOT NAME to cycle number 0-7 and 0-4 as port index as following expected result.

I had tried to implement it by using loop and get the following result.
The result is wrong and I know it is caused by the nested loop.

Code:

n = 1
m = 2
p = 0
test_1 = ''
test_2 = ''          
port_index_file = open('display.txt', 'r+')
#Get the position of port index
port_index_init = port_index_file.readline().find('0', 60) 
port_index_file.seek(port_index_init, 0) 
#Check the "SLOT NAME" in each line is the same or not
while n <= 13:
    test_1 = subprocess.check_output("cat display.txt | awk NR==%s | awk '{print $3}'" % (n), shell=True)
    test_2 = subprocess.check_output("cat display.txt | awk NR==%s | awk '{print $3}'" % (m), shell=True)
    test_1 = test_1[:-1].decode()
    test_2 = test_2[:-1].decode()
    #Change the values of port index
    port_index_file.write(str(p))
    if test_2 == test_1:
        p = p + 1
    else:
        p = 0
    n = n + 1
    m = m + 1
port_index_file.close()

If I want to get the expected result above, how do I modify my program?
Any advice would be appreciate, thanks.

I guess you mean: when two consecutive rows use the same slot name, the port index should keep counting up. When a new value is seen for the slot name, the port index should start over again at 0. Is that right?

Hi @kknechtel,
Yes, correct, sorry for my poor description and thank you for your additional explanation. :grin:

That would require all rows to be ordered/grouped by slot name in the file which seems an unnecessary constraint. Better to just index on that field. E.g. myprog.py:

!/usr/bin/env python3
import fileinput

slots = {}
for line in fileinput.input():
    fields = line.split()
    slot = fields[2]
    num = slots.get(slot, 0)
    slots[slot] = num + 1
    fields[3] = str(num)
    print('\t'.join(fields))

Run that program as myprog.py display.txt

1 Like

Hi @bulletmark,
Thanks for your help.
I had modified and integrated the code you provide into my program.
Now it works very well.
Thank you. :grin: