2

Using grep, how would I do this in one command line?

I have this so far grep '\$[0-9][0-9]\.[0-9][0-9]' money.txt with various strings in the text file, but I'm having issues satisfying some of my conditions.

I'm trying to search for any lines that contain dollar values from $10.00 to $99.99 (dollar sign+keeping two digits after the decimal point), and mine will catch everything, but that even includes when you have text before or after it

e.g. abc$15.64, abc$15.64xyz, $15.64abc

I want them to only be caught if there's a space either before (e.g. end of the line), after (start of the line), before & after (middle of the line), or none at all (e.g. only string in the line).

I've tried adding \s but then it doesn't print anything at all (even something valid like abc $15.64 xyz), though they print fine if I make them optional (using *). So, I assume it just completely ignores \s since it doesn't seem to satisfy anything.

Note: I only want to make spaces optional because I need it to also print the line when the dollar values are at the start or end of the line, in which case there wouldn't be a space before or after them, respectively. Even if I could get the \s to work, making it optional would still match strings like abc$15.64xyz

Any idea how I could make this work?

Thanks.

2 Answers 2

1

you simply must specify that regexp starts either with start of line or space. And ends with either end of line or space. I hope that's what you want.

egrep '(^| )\$[0-9][0-9]\.[0-9][0-9]($| )' money.txt
2
  • Yes! That's exactly it. Just to be clear (^| ) just means start of the line, or a space right? I guess I just didn't think I could use ^ and $ like that. Thanks!
    – Adam
    Jan 30, 2013 at 20:16
  • > Just to be clear (^| ) just means start of the line, or a space - right
    – sparkie
    Jan 30, 2013 at 20:20
0

Just for preciseness in your goal to gather just the range $10.00 to $99.99 you'd want to modify Sparkie's perfect answer like this:

egrep '(^| )\$[1-9][0-9]\.[0-9][0-9]\($| )' money.txt

Thanks Sparkie for the egrep tip, I've never understood how to get an 'or' into a grep search, very cool and added to my kit bag.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .