[ Date Index ] [ Thread Index ] [ <= Previous by date / thread ] [ Next by date / thread => ]
On Tue, 28 Dec 2010, Simon Williams wrote:
Afternoon all. How can I make grep or sed print a matching group *only*?So far the only solution I have been able to find is to use grep to pick out the line and then use sed to substitute the entire line for just the matching group, like this:grep '^foo .* bar$' | sed 's/foo \(.*\) bar/\1/'This is clearly stupid and there must be a better way. Why can't I do something like this?
I don't think it's stupid at all. You're using the unix principle to do exactly what it was designed to do - have a program do one thing well. In this case you have a good program that matches lines based on regular expressions (grep - which stands for global regular expression fwiw) and a good program for chopping bits out of lines base on regular expressions (sed - stream editor) and you're using them together.
See: http://catb.org/~esr/writings/taoup/html/ch01s06.html Section (i) etc.
grep '^foo (.*) bar$' -[some option] or: sed '/^foo (.*) bar$/\1/'
Because then you'd have to write the code for '-[some option]' thus bloating the size of the original, and adding in functionality that might only be used once in a blue moon.
This isn't the first time I've been driven completely insane by this problem. I don't understand why it's so difficult.Can anyone help me?
You don't need help - you solved the problem yourself on the first line. Why look for something more complex?
Or you could write a program in AWK or Perl...I mean, imagine if someone bloated the grep program with a recursive descent routine when find does it perfectly well...
Gordon -- The Mailing List for the Devon & Cornwall LUG http://mailman.dclug.org.uk/listinfo/list FAQ: http://www.dcglug.org.uk/listfaq