Skip to content
shellhacks.dev
Text Processing

Extract the First Number in a Line with grep and head

Extract the first number in a line with grep -oE '[0-9]+' piped to head -n 1, with sed and a capture group, or with Bash's BASH_REMATCH. Print nothing when absent.

1 min read
Summarize in AI

A line such as a build message holds several numbers and you want only the first.

Shell
line='build 42 of 1337 passed'
echo "$line" | grep -oE '[0-9]+' | head -n 1
echo "$line" | sed -E 's/[^0-9]*([0-9]+).*/\1/'
[[ $line =~ [0-9]+ ]] && echo "${BASH_REMATCH[0]}"
echo "no digits here" | sed -E 's/[^0-9]*([0-9]+).*/\1/'
echo "no digits here" | sed -nE 's/[^0-9]*([0-9]+).*/\1/p'
Text
42
42
42
no digits here

grep -oE '[0-9]+' prints every match on its own line, so head -n 1 keeps the first; each of the three methods printed 42. The sed form replaces the whole line with its first group, [^0-9]*([0-9]+).* capturing the digits after any non-digits. The Bash form uses [[ =~ ]], which leaves the match in BASH_REMATCH[0] and starts no process. See grep options and Conditional Constructs.

When a line has no digits, sed prints the line unchanged, as the second to last result shows, so add -n and a p flag to print nothing instead. These patterns find digits only, not signs, decimals or thousands separators. Use -m 1 when you only need the first line, not the first number.

Share

More snippets

Text Processing

Replace Only the Nth Match on a Line with sed

Replace only the second or a later match on a line with a numeric flag on the s command, and add g to replace from that match onward. The count restarts on every line.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.