0

I have the below output. I want to extract the number before the text. Like for example, I grep for TrainIdentifyBusinessError and I want 1612 to be displayed. I grep for TrainIdentifyTechnicalError and I want 3 to be displayed.

1612 TrainIdentifyBusinessError 252 TrainIdentifySuccess 3 TrainIdentifyTechnicalError
  • 1
    Are these on diferent lines? – heemayl Dec 21 '16 at 14:14
  • You mean "below input", right? – xhienne Dec 21 '16 at 14:43
3

You could use sed instead... for example

$ sed -nr 's/.*( |^)([0-9]+) TrainIdentifyBusinessError.*/\2/p' file
1612

or

$ sed -nr 's/.*( |^)([0-9]+) TrainIdentifySuccess.*/\2/p'
252

or

$ sed -nr 's/.*( |^)([0-9]+) TrainIdentifyTechnicalError.*/\2/p'
3
  • -n don't print anything until we ask for it
  • -r use ERE
  • .* any number of any chars on the line
  • ( |^) space or start of line
  • ([0-9]+) one or more digits and (save this)
  • \2 back reference to the second (saved pattern)
  • p print the edited line

Afterthought... if you need to do this regularly you could make a shell function (add to your shell's ~/.*rc file, for example, ~/.bashrc if you use bash), for example:

getnum() { sed -nr 's/.*( |^)([0-9]+) TrainIdentify'"$1"'.*/\2/p' "$2" ; }

Usage example (specify the field and the filename on the command line - if the file is always the same file, you could put the full path to it inside the function instead of "$2"):

$ getnum BusinessError file
1612
$ getnum TechnicalError file
3
$ getnum Success file
252
2

This can be solved using the Perl extension for grep (the -P flag). To get 3 from TrainIdentifyTechnicalError:

$ echo "1612 TrainIdentifyBusinessError 252 TrainIdentifySuccess 23 TrainIdentifyTechnicalError" | grep -Po "[[:digit:]]+ *(?=TrainIdentifyTechnicalError)"
23 

To get 1612 from TrainIdentifyBusinessError

$ echo "1612 TrainIdentifyBusinessError 252 TrainIdentifySuccess 23 TrainIdentifyTechnicalError" | grep -Po "[[:digit:]]+ *(?=TrainIdentifyBusinessError)"
1612 

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.