Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
grep: combine --invert-match and --only-matching [SOLVED]
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Portage & Programming
View previous topic :: View next topic  
Author Message
alex.blackbit
Advocate
Advocate


Joined: 26 Jul 2005
Posts: 2395

PostPosted: Thu Feb 21, 2013 2:33 pm    Post subject: grep: combine --invert-match and --only-matching [SOLVED] Reply with quote

Hi,

I try to use grep to remove a pattern in a string.
Matching for that pattern works
Code:
$ echo "123 foo" | grep --only-matching "^[[:digit:]]\+ "
123
$

The inverse does not
Code:
$ echo "123 foo" | grep --invert-match --only-matching "^[[:digit:]]\+ "
$

I expected to get "foo".
Do I do something wrong?


Last edited by alex.blackbit on Tue Feb 26, 2013 3:26 pm; edited 1 time in total
Back to top
View user's profile Send private message
mv
Advocate
Advocate


Joined: 20 Apr 2005
Posts: 4105

PostPosted: Thu Feb 21, 2013 2:38 pm    Post subject: Reply with quote

You look at the wrong tool: grep essentially can only print a line or not. What you probably want is sed. Something like
Code:
echo "123 foo" | sed -ne 's/^[[:digit:]]\+ //p'
Back to top
View user's profile Send private message
alex.blackbit
Advocate
Advocate


Joined: 26 Jul 2005
Posts: 2395

PostPosted: Thu Feb 21, 2013 3:02 pm    Post subject: Reply with quote

Thanks for the answer, mv.
grep --only-matching _does_ print only part of a line though.
In my opinion it is not obvious why this does not work for the inverted match case.
Back to top
View user's profile Send private message
Genone
Retired Dev
Retired Dev


Joined: 14 Mar 2003
Posts: 9011
Location: beyond the rim

PostPosted: Thu Feb 21, 2013 3:52 pm    Post subject: Reply with quote

By default grep shows lines matching the given expression.
--invert-match will show lines not matching the expression.
--only-matching will only show the part of the line that matches.

So both together will show matching parts of non-matching lines. --invert-match does NOT invert the passed expression which would be required for your use case.
Back to top
View user's profile Send private message
alex.blackbit
Advocate
Advocate


Joined: 26 Jul 2005
Posts: 2395

PostPosted: Tue Feb 26, 2013 3:25 pm    Post subject: Reply with quote

Thanks Genone, that's a very good explanation.
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Portage & Programming All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum