Sunday, January 28, 2024

[SOLVED] Python or sed one-liner to delete a line that starts with any digit and has one string

Issue

I would like to delete any line that starts with a number not followed by a delimiter. Thanks in advance.

Input data [modified from href="https://stackoverflow.com/questions/57469742/using-sed-to-replace-a-newline-that-starts-with-any-digit">here]:
Test 1,2,3,
41
Test 5,6,7,
8800 
8800 8800 
8800.
8800.0
8,800
Test 9, 10
Test 11, 12
Expected output:
Test 1,2,3,
Test 5,6,7,
8800 8800 
8800.
8800.0
8,800
Test 9, 10
Test 11, 12
My attempt (removes all numbers):
> sed 's/^[[:digit:]]//g' temp_test_001.txt

Test ,,,

Test ,,,


.
.
,
Test ,
Test ,

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.



Answered By - alec_djinn
Answer Checked By - Marie Seifert (WPSolving Admin)