Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Big Dave

macrumors 6502
Original poster
Nov 27, 2007
314
25
Crestview, Fl
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.
 
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.
 
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
 
Last edited:
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.

Which I'm pretty sure Apple uses.

OS X is a BSD, they use BSD sed.
 
Last edited:
Simplified: ^\d{2}\.\d{2}$

This declares a start and end and must match a numeric value
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.