1

Using Bash, how can I find the first number in a string and then take the rest of the string?

For example, I have the following string -

SomeText.MoreText.Whatever.1.2.3.4-branch.ext

And I wish to end up with this -

1.2.3.4-branch.ext

I've found several answers that suggest how to find numbers (such as this question), but nothing that finds and returns a portion of a string.

10
  • I have solved this using grep and a basic regular expression. What have you tried this far? Oct 12 '16 at 10:48
  • @maulinglawns - "I have solved this using grep and a basic regular expression" - Care to share? After all, isn't that the idea of a question/answer site such as this...
    – David Gard
    Oct 12 '16 at 10:52
  • @maulinglawns - Actually, don't worry, someone esle was kind enough to share an answer.
    – David Gard
    Oct 12 '16 at 10:53
  • 1
    [[ $string =~ [0-9].* ]] && echo $BASH_REMATCH Oct 12 '16 at 10:55
  • @SatoKatsura - Thanks for the contribution, that also does the job just fine.
    – David Gard
    Oct 12 '16 at 10:56
2

With grep, extracting only the matched portion (-o):

grep -o '[0-9].*'
  • [0-9] will match the first digit, and .* will match the rest

Example:

$ grep -o '[0-9].*' <<<'SomeText.MoreText.Whatever.1.2.3.4-branch.ext'
1.2.3.4-branch.ext
2
  • 1
    This does the same in most POSIX shells without the need (and the time expense) of calling an external utility: echo "${var#"${var%%[0-9]*}"}".
    – ImHere
    Oct 12 '16 at 11:57
  • @sorontar, please post that as an answer.
    – agc
    Oct 12 '16 at 12:29
0

The simplest and available in most POSIX shells is:

$ var='SomeText.MoreText.Whatever.1.2.3.4-branch.ext'

$ echo "${var#"${var%%[0-9]*}"}"
1.2.3.4-branch.ext

In this way there is no need to call any external utility (expr, sed, awk, etc) and the time expense to call such utility is also avoided (for short strings such as in this case, for long strings (10's of k's) the shell is very slow).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.