How do I grab only the number from a command line output.

For example, I have a program which on being run outputs a string like

submitted batch with job number 12345

I would like to grab only the number 12345 and pipe it to another program.


The simplest form to get only the number from the string you have provided is as follows.

string="submitted batch with job number 12345"
echo $string | grep -o '[0-9]\+'

This will fail if the string or output of your program does include a second number group like

string="submitted 1 batch with job number 12345"

In that case, you would could use sed to e.g. search for the string number and only match for numbers after that occurrence.

echo $string | sed -n 's/^.*number\ \([0-9]\+\)/\1/p'
  • Thanks! I'm not able to accept the answer due to my rating but this works wonderful! – Adi279 Oct 10 '17 at 18:53
  • We can use | tail -1 to cut only the last result, if there are more than one. – pa4080 Oct 10 '17 at 18:54
  • Save the pipe subshell with a here string, e.g. grep -o '[0-9]\+' <<< "$string". – dessert Oct 10 '17 at 20:28
  • No need to specify the beginning of the line and to escape the space character in quotes – and no need to negate and print it: sed 's/.*number \([0-9]\+\)/\1/' <<< "$string" – dessert Oct 10 '17 at 20:37

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.