I have the following grep:

grep -Po 'href="(http://.*)">Transcript.* - ([0-9]*)\. (.*)</a>'

I would like to print out the match groups. Is there a way to do this without Perl/Python? I tried using sed, but I couldn't manage to make it work -- probably due to syntax issues, I'm not really sure what needs to be escaped and what not.

  • 2
    Can you show an example URL that you're trying to parse with grep? – slm Oct 4 '13 at 12:50
sed -n 's|.*href="\(http://[^"]*\)">Transcript.* - \([0-9]*\)\. \(.*\)</a>|\1:\2:\3|p'

That only works if there's only one link per line.

With perl:

perl -lne 'print for m|href="(http://.*?)">Transcript.*? - (\d*)\. (.*?)</a>|g'

A native bash solution might work for you. This matches the entire line to the regular expression so will only work with one link per line scenarios

pat='href="(http://.*)">Transcript.* - ([0-9]*)\. (.*)</a>'
while IFS= read -r line; do 
   [[ $line =~ $pat ]] && 
   echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]}"
done <file.txt

grep can only print either the whole line or the part which matched the single pattern (or the filename, I guess). However, since you're using a perl regex, you may want to try pcregrep, which has an additional optional parameter to the -o flag specifying the parenthetical group to show. As in

sauer@humpy:~$ echo ab12cd34ef | pcregrep -o1 '.*?(\d+).*?(\d+).*'
sauer@humpy:~$ echo ab12cd34ef | pcregrep -o2 '.*?(\d+).*?(\d+).*'

Unfortunately, you can not specify multiple -o options (probably because you'd then need a separator and things would get ugly). But if you're doing something simple, I suppose you could just repeat the pcregrep multiple times.

Also note that there can be no space between the "o" and match number in the command, since -o with no argument behaves the same as regular grep.

Personally, I'd just use perl.

sauer@humpy:~$ echo ab12cd34ef | perl -plne 's/^.*?(\d+).*?(\d+).*$/$1:$2/'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.