1

With a sed cmd I want to print all occurrences of a pattern in one line. I know how to do this with grep -Pe and with awk. I started with:

$ sed 's/^.*label="\(.*\)" selected.*$/\1/g' <(echo 'smkj sld/6_ !label="snd 1" selected>lms slks.;label="snd 2" selected>lkwnl  wlkmlabel="snd 3" selected>The following should not be printedlabel="')
snd 3

However the above only prints snd 3, i.e. the string between the last occurrence of label=" and " selected. How do I include all occurrences of the regex on any one line ?

  • Are you parsing an XML document? What does that document look like and what data do you need to extract from it in what format? – Kusalananda Mar 21 at 8:31
  • 2
    sed always matches the longest match for ^.*label=". That is why the last "label" is printed and everything else gets substituted. sed is simply not the right tool to do that job. – RoVo Mar 21 at 9:35
  • @RoVo: Might be worth a one-line answer on your part just to highlight the content of your comment. I have been using sed for quite some time now, read quite a bit about it, consulted the infopage (not just the manpage), other source and tutorials, and consistently "missed" the "longest match" detail you appropriately mention. Tx. – Cbhihe Mar 21 at 12:11
  • 1
    Yes, maybe you missed that. From gnu sed manual: "Note that the regular expression matcher is greedy, i.e., matches are attempted from left to right and, if two or more matches are possible starting at the same character, it selects the longest." – RoVo Mar 21 at 12:18
  • @Kusalananda: No XML here at all. The data looks completely unstructured. It only has those two tags label and selected as shown. – Cbhihe Mar 21 at 12:21
1

Using GNU sed we can generate the desired output as shown below:

$ sed -Ee '
     s/label="([^"]+)" selected[>]/\n\1\n/
     s/.*\n(.*\n)/\1/
     /\n/!d
     P;D
' input.txt

Outputs:

snd 1
snd 2
snd 3

With Perl you can do it as a one liner:

$ perl -lne 'print for /label="([^"]+)" selected[>]/g' input.txt

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.