How do I get a string after the first occurrence of a number?
For example, I have a file with multiple lines:
JavaScript
x
34 abcdefg
10 abcd 123
999 abc defg
I want to get the following output:
JavaScript
abcdefg
abcd 123
abc defg
Thank you.
Advertisement
Answer
Imagine the following two input files :
JavaScript
001 ham
03spam
3 spam with 5 eggs
A quick solution with awk would be :
JavaScript
awk '{sub(/[^0-9]*[0-9]+/,"",$0); print $1}' <file>
This line substitutes the first string of anything that does not contain a number followed by a number by an empty set (""
). This way $0
is redefined and you can reprint the first field or the remainder of the field. This line gives exactly the following output.
JavaScript
ham
spam
spam
If you are interested in the remainder of the line
JavaScript
awk '{sub(/[^0-9]*[0-9]+ */,"",$0); print $0}' <file>
This will have as an output :
JavaScript
ham
spam
spam with 5 eggs
Be aware that an extra " *"
is needed in the regular expression to remove all trailing spaces after the number. Without it you would get
JavaScript
awk '{sub(/[^0-9]*[0-9]+/,"",$0); print $0}' <file>
ham
spam
spam with 5 eggs