2

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
2
  • 1
    Are these on diferent lines?
    – heemayl
    Dec 21, 2016 at 14:14
  • You mean "below input", right?
    – xhienne
    Dec 21, 2016 at 14:43

2 Answers 2

4

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
1
  • This is just what I was looking for, except the number has a decimal point in it. Dec 26, 2019 at 18:23
3

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 
1
  • With slight modification you can get DP-1-1 refresh rate. For example: xrandr | sed -n '/^DP-1-1/,/^[^ ]/p' | grep -Po '[[:digit:].]+ *(?=\*+)' returns: 53.98. Dec 26, 2019 at 19:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .