| View previous topic :: View next topic |
| Author |
Message |
alex.blackbit Advocate

Joined: 26 Jul 2005 Posts: 2390
|
Posted: Thu Feb 21, 2013 2:33 pm Post subject: grep: combine --invert-match and --only-matching [SOLVED] |
|
|
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 |
|
 |
mv Advocate


Joined: 20 Apr 2005 Posts: 3135
|
Posted: Thu Feb 21, 2013 2:38 pm Post subject: |
|
|
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 |
|
 |
alex.blackbit Advocate

Joined: 26 Jul 2005 Posts: 2390
|
Posted: Thu Feb 21, 2013 3:02 pm Post subject: |
|
|
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 |
|
 |
Genone Retired Dev


Joined: 14 Mar 2003 Posts: 8861 Location: beyond the rim
|
Posted: Thu Feb 21, 2013 3:52 pm Post subject: |
|
|
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 |
|
 |
alex.blackbit Advocate

Joined: 26 Jul 2005 Posts: 2390
|
Posted: Tue Feb 26, 2013 3:25 pm Post subject: |
|
|
| Thanks Genone, that's a very good explanation. |
|
| Back to top |
|
 |
|