Cut a file delimited on a number with one or more digits
7,255
Solution 1
$ awk -F'[0-9]' '{ print $1 }' file
John Smith
Amy Brown and Sally Williams
Sunny's
With -F'[0-9]'
we say that digits are to be considered field separators in the input data, and with print $1
we output the first digit-separated field.
Change -F'[0-9]'
to -F' *[0-9]'
to also get rid of any spaces before the digit.
Solution 2
And a sed
solution:
echo "John Smith 1234 Main Street
Amy Brown and Sally Williams 9 Drury Lane
Sunny's 1000 Brown Avenue" | sed 's/ *[0-9].*$//'
John Smith
Amy Brown and Sally Williams
Sunny's
Solution 3
GNU grep:
grep -Po '.*?(?=\s*\d)' file
Solution 4
With GNU grep
grep -o '^[^[:digit:]]*' file
(note that it won't output anything for lines like 123foo
, that is lines where the part left of the digits is empty).
Related videos on Youtube
Author by
mttpgn
Updated on September 18, 2022Comments
-
mttpgn over 1 year
I'm looking for a way to extract the first column of a text file that has no specific delimiters except for arbitrary digits that begin the next column. Example:
John Smith 1234 Main Street Amy Brown and Sally Williams 9 Drury Lane Sunny's 1000 Brown Avenue
Expected output would be:
John Smith Amy Brown and Sally Williams Sunny's
It appears that
cut
doesn't support functionality such ascut file.txt -d {0..9} -f 1
Solutions can use any standard unix utility.
-
tink over 6 yearsLine 2 doesn't have multi digits.
-