lines with matches as a new column

Question:

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:

Val1tPosition1
Val2tPosition1
Val3tPosition1
Val4tPosition2
Val10tPosition2
Val5tPosition2
Val20tPosition3
Val200tPosition3

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

Asked By: gusa10

||

Answers:

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
Answered By: Nick

use this code:

with open('aa.txt', 'r') as f:
lines = f.readlines()
f.close()
position_index = []
positions_values = {}
for i, j in enumerate(lines, start=0):
    if 'Position' in j:
        position_index.append(i)

for k in position_index:
    positions_values[lines[k]] = lines[k+1: k+4]

for position, vals in positions_values.items():
    position = position.replace('n', '')
    for v in vals:
        v = v.replace('n', '')
        print(v, 't', position)
Answered By: alirah75
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.