Python: concatenate sequential lines if separated by backslashes and remove backslashes

I have a file that contains shell commands. Each command can be split over multiple lines (using a backslash at the end):
for example

  cmd1 -opt1 \  
    -opt2 val2  \  
    -opt3 val3 val4

      

I want to join sequential lines if they are separated by a backslash at the end. I also want to remove the backslash after joining.

The problem is similar:
Input:
['abc', 'def \\', 'ghi \\', 'jkl', 'yyy \\', 'zzz']
Output:
['abc', 'def ghi jkl', ' yyy zzz ']

iterates over only list solution?

with open("cmd", "r") as fp:
    cmd = ""
    cont = False
    list = []
    for line in fp:
        line = line.rstrip("\n")
        if line.endswith('\\'):
            line = line[:-1]
            if cont:
                cmd = cmd + line
                continue
            if cmd:
                list.append(cmd)
            cmd = line
            cont = True
        else:
            if cont:
                cmd = cmd + line
                if cmd:
                    list.append(cmd)
                cmd = ""
                continue
            cont = False
    print(list)

      

+3


source to share


2 answers


cmd = ['abc', 'def \\', 'ghi \\', 'jkl', 'yyy \\', 'zzz']

res = "\ n" .join (cmd) .replace ("\\\ n", "") .splitlines ()

print (resolution)



=> ['abc', 'def ghi jkl', 'yyy zzz']

Clodion

+3


source


iterates over only list solution?

You will need to evaluate each line for the concatenation indicator and add the next line. Yes, you need to get through.



Here's a function that uses a generator, so all input is not required in memory.

>>> sample = ['abc', 'def \\', 'ghi \\', 'jkl' , 'yyy \\', 'zzz']
>>>
>>> def join_lines(sequence):
...   i = iter(sequence)
...   buff = ''
...   try:
...     while True:
...       line = i.next()
...       if line.endswith('\\'):
...         line = line[:-1]
...         buff += line
...       else:
...         if buff:
...           buff += line
...           yield buff
...           buff = ''
...         else:
...           yield line
...   except StopIteration:
...     if buff:
...       yield buff
...
>>> print sample
['abc', 'def \\', 'ghi \\', 'jkl', 'yyy \\', 'zzz']
>>> print list(join_lines(sample))
['abc', 'def ghi jkl', 'yyy zzz']

      

+1


source







All Articles