Home > Blockchain >  lines with matches as a new column
lines with matches as a new column

Time:10-17

I have a file:

Position1
Val1
Val2
Val3
Position2
Val4
Val10
Val5
Position3
Val20
Val200

and I would like to move the line with the word "Position" as a new column, tab separated:

Val1\tPosition1
Val2\tPosition1
Val3\tPosition1
Val4\tPosition2
Val10\tPosition2
Val5\tPosition2
Val20\tPosition3
Val200\tPosition3

Val vary in quantity, so Position(s) have different amount of Val. I am happy to make it in python or unix shell

CodePudding user response:

You can loop the lines in your file, saving the position string when you find it and outputting a new line otherwise:

pos = ''
for line in file:
    if line.startswith('Position'):
        pos = line
        continue
    print(f'{line}\t{pos}')

Output (for your sample data):

Val1    Position1
Val2    Position1
Val3    Position1
Val4    Position2
Val10   Position2
Val5    Position2
Val20   Position3
Val200  Position3
  • Related