Skip to content
Advertisement

grep string after first occurrence of numbers

How do I get a string after the first occurrence of a number?

For example, I have a file with multiple lines:

  34 abcdefg
10 abcd 123
    999 abc defg

I want to get the following output:

abcdefg
abcd 123
abc defg

Thank you.

Advertisement

Answer

Imagine the following two input files :

  001 ham
03spam
  3 spam with 5 eggs

A quick solution with awk would be :

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.

ham
spam
spam

If you are interested in the remainder of the line

awk '{sub(/[^0-9]*[0-9]+ */,"",$0); print $0}' <file>

This will have as an output :

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

awk '{sub(/[^0-9]*[0-9]+/,"",$0); print $0}' <file>

 ham
spam
 spam with 5 eggs
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement