Search code examples
pythonregexwindowstextsed

One-liner to delete any line that starts with a number not followed by a delimiter


This two-line python code works. Can it be made concise? Thanks.

temp_test_001 = '''
Test 1,2,3,
41
Test 5,6,7,
8800
8800 8800 
8800.
8800.0
8,800
Test 9,10
Test 11,12
'''.split('\n')

lines = '' 
for line in enumerate(temp_test_001): lines += [line[1] + '\n',''][line[1].isnumeric()]
print(lines)

Test 1,2,3,
Test 5,6,7,
8800 8800 
8800.
8800.0
8,800
Test 9,10
Test 11,12

Solution

  • Here is an ugly one-liner in Python

    txt = '''
    Test 1,2,3,
    41
    Test 5,6,7,
    8800 
    8800 8800 
    8800.
    8800.0
    8,800
    Test 9, 10
    Test 11, 12
    '''
    
    print('\n'.join([line for line in txt.split('\n') if not all(map(lambda x: x in '0123456789', line.strip()))]))
    
    Test 1,2,3,
    Test 5,6,7,
    8800 8800 
    8800.
    8800.0
    8,800
    Test 9, 10
    Test 11, 12
    

    You can execute it from the shell as one-liner using

    python -c "import sys; print(''.join([line for line in open(sys.argv[1]).readlines() if not all(map(lambda x: x in '0123456789', line.strip()))]))" text.txt
    

    Where text.txt is your input text file.