Results 1 to 3 of 3

Thread: sed: Wildcard is Eating Too Much

  1. #1
    Join Date
    Mar 2009
    Beans
    927
    Distro
    Ubuntu 12.04 Precise Pangolin

    Lightbulb [SOLVED] sed: Wildcard is Eating Too Much

    I'm trying to remove all comments from a piece of code:
    Code:
    ~ $ echo "code # comments # more comments" | sed 's_^\(.*\)#.*$_\1_
    code # comments 
    As you can see the first wildcard .* is eating as much text as it possibly can, all the way up to the last #. How can I make it eat the bare minimum, only up to the first #?
    If this is not possible, then is there some way to process sed backwards so that the last wildcard gets processed first?

    Two ways of solving the problem (thanks to MadCow108):
    Code:
    ~ $ echo "code # comments # more comments" | sed 's_^\([^#]*\).*$_\1_'
    code 
    or
    Code:
    ~ $ echo "code # comments # more comments" | perl -p -e 's/^(.*?)#.*$/\1/'
    code 
    Last edited by Penguin Guy; August 31st, 2009 at 05:03 PM.

  2. #2
    Join Date
    Apr 2009
    Location
    Germany
    Beans
    2,134
    Distro
    Ubuntu Development Release

    Re: sed: Wildcard is Eating Too Much

    you could use this:
    echo "code # comments # more comments" | sed 's_^\([^#]*\).*$_\1_'

    alternativly you could use perl:
    echo "code # comments # more comments" | perl -p -e 's/^(.*?)#.*$/\1/'

    where .*? means non greedy matching
    http://docstore.mik.ua/orelly/perl/cookbook/ch06_16.htm
    Last edited by MadCow108; June 14th, 2009 at 03:41 PM.

  3. #3
    Join Date
    Mar 2009
    Beans
    927
    Distro
    Ubuntu 12.04 Precise Pangolin

    Talking Re: sed: Wildcard is Eating Too Much

    Quote Originally Posted by MadCow108 View Post
    you could use this:
    echo "code # comments # more comments" | sed 's_^\([^#]*\).*$_\1_'

    alternativly you could use perl:
    echo "code # comments # more comments" | perl -p -e 's/^(.*?)#.*$/\1/'

    where .*? means non greedy matching
    http://docstore.mik.ua/orelly/perl/cookbook/ch06_16.htm
    Thanks, both solutions work perfectly!

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •