Reputation: 23
I have the following sample strings:
Program exiting with code: 0.
Program exiting with code: 1.
Program exiting with code: 10.
I want grep to return values after the matching pattern "Program exiting with code:". However I do not need the period at the end. I have tried:
grep "Program exiting with exit code:" dataload.log | sed 's/^.*.: //'
The above command returns:
0.
1.
10.
I want to ignore the period at end. I picked up the above command from somewhere.
Can someone describe what each keyword represents and provide me with a regex that will only provide me with the value without period?
sed
, awk
, perl
or any other way is fine with me.
Upvotes: 2
Views: 1106
Reputation: 22428
This is another way:
grep -oE 'Program exiting with code:\s*[0-9]+' dataload.log |grep -oE '[0-9]+$'
Output of the first grep command is:
Program exiting with code: 0
Program exiting with code: 1
Program exiting with code: 10
Then you just grep
the last digits.
Upvotes: 0
Reputation: 7783
sed 's/^.*.: //'
First of all this is a substition regular expression, as denoted by the s
at the start. The part in the first / /
is what to match and the second / /
is what to replace it with.
The characters in the first (match) part of the expression are all special regular expression characters.
A full list of what they mean can be found here: http://www.rexegg.com/regex-quickstart.html
The match means:
^
- At the start of the line
.
- Match any character
*
- Any number of times
.
- Match any character
:
- Match a colon
- Match a space
And then that is all replaced with nothing. That is why the period at the end is kept because it removes everything up to Program exiting with code:
, which leaves 1.
It's worth playing around with an interactive tool to test different regular expressions on your string, e.g. http://www.regexr.com/
You can probably just substitute/remove everything that is not a number in your case: 's/[^0-9]//g'
.
Upvotes: 0
Reputation: 410
Your solution is just fine if you extend it with a cut
command:
grep "Program exiting with code:" dataload.log | sed 's/^.*.: //' | cut -d"." -f1
Upvotes: -1
Reputation: 289795
Just use grep with a look-behind and catch only digits:
$ grep -Po '(?<=Program exiting with code: )\d*' file
0
1
10
Upvotes: 2