How to match and keep the first number in a line using sed?
regex, sed
Solution
To complement the `sed` solutions, here's an `awk` alternative (assuming that the goal is to extract the 1st number on each line, if any (i.e., ignore lines without any numbers)):
awk -F'[^0-9]*' '/[0-9]/ { print ($1 != "" ? $1 : $2) }'
- `-F'[^0-9]*'` defines any sequence of non-digit chars. (including the empty string) as the field separator; `awk` automatically breaks each input line into fields based on that separator, with `$1` representing the first field, `$2` the second, and so on.
- `/[0-9]/` is a pattern (condition) that ensures that output is only produced for lines that contain at least one digit, via its associated action (the `{...}` block) - in other words: lines containing NO number at all are ignored.
- `{ print ($1!="" ? $1 : $2) }` prints the 1st field, if nonempty, otherwise the 2nd one; rationale: if the line starts with a number, the 1st field will contain the 1st number on the line (because the line starts with a field rather than a separator; otherwise, it is the 2nd field that contains the 1st number (because the line starts with a separator).
Problem
Question Let's say I have one line of text with a number placed somewhere (it could be at the beginning, in the middle or at the end of the line). How to match and keep the first number found in a line using `sed`? Minimal example Here is my attempt (following this page of a tutorial on regular expressions) and the output for different positions of the number: ``` $echo "SomeText 123SomeText" | sed 's:.*\([0-9][0-9]*\).*:\1:' 3 $echo "123SomeText" | sed 's:.*\([0-9][0-9]*\).*:\1:' 3 $echo "SomeText 123" | sed 's:.*\([0-9][0-9]*\).*:\1:' 3 ``` As you can only the last digit is kept in the process whereas the desired output should be `123`...