Regular expression / sed question.

Discussion in 'Mac Programming' started by Big Dave, Feb 26, 2014.

  1. Big Dave macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #1
    I can use sed to return a line that contains my search for regular expressions, but is there a way to only return the regular expression itself instead of the whole line?

    Code:
    sed -n '/[0-9][0-9]\.[0-9][0-9]/,p' file
    The above one liner will return a whole line but I would like to return the item searched. Something like 99.99.
     
  2. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
  3. Big Dave thread starter macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
    #4
    I think I can get close enough. If I use:

    Code:
    sed -n '/^.*[0-9][0-9]\.[0-9][0-9]/p' file
    The first field is my desired target. I can grab it with awk from there.
     
  4. chown33, Feb 26, 2014
    Last edited: Feb 26, 2014

    chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #5
    The whole thing can be done in awk.

    Code:
    awk 'match($0,"[0-9][0-9]\.[0-9][0-9]")  { print substr($0,RSTART,RLENGTH) }' \
      data.txt
    
    File data.txt:
    Code:
    I paid 12.34 for ten ducklings.
    I sold them for 23.95 each.
    What was the profit?
    
    If a kangaroo travels 42.50 furlongs 
    in 10.39 fortnights, does its velocity
    exceed that of a score of African swallows
    transporting 38.30 cubic inches of coconuts?
    
    
    Output:
    Code:
    12.34
    23.95
    42.50
    10.39
    38.30
    

    Or use perl's tagged regex'es:
    http://www.tjhsst.edu/~dhyatt/perl/exA.html
     
  5. randian macrumors 6502a

    Joined:
    Jan 15, 2014
    #6
    Which I'm pretty sure Apple uses.
     
  6. subsonix, Feb 26, 2014
    Last edited: Feb 26, 2014

    subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #7
    FWIW I usually use grep -oE for this, the -o flag fetches only the part that matches the pattern, -E uses extended regex. Not sure if it will help you here but..

    Example:

    Code:
    grep -oE "[0-9][0-9]\.[0-9][0-9]" text.txt
    
    Will isolate numbers like 99.99 from text.txt.

    OS X is a BSD, they use BSD sed.
     
  7. Big Dave thread starter macrumors 6502

    Joined:
    Nov 27, 2007
    Location:
    Crestview, Fl
  8. -RATBOY- macrumors newbie

    Joined:
    Feb 26, 2014
    #9
    Simplified: ^\d{2}\.\d{2}$

    This declares a start and end and must match a numeric value
     
  9. mfram macrumors 65816

    Joined:
    Jan 23, 2010
    Location:
    San Diego, CA USA
    #10
    No, that expression says it matches only a line which contains the numeric value, but nothing else.

    Thus it matches:
    15.21

    But not:
    That costs 15.21!
     

Share This Page