tags:

views:

133

answers:

8

Here is the line of text:

SRC='999'

where 999 can be any three digits.

I need a grep command that will return me the 999. How do I do this?

A: 

Platform grep or general regular expression?

Regex

SRC\=\'(\d{3})\'
Quintin Robinson
A: 

why grep? How about..

substr("SRC='999'",6,3)
yankee2905
This would be faster than running a regular expression, with the tradeoff that it would not handle any change in the format of the data (e.g. two digits instead of three).
qid
+2  A: 

Are the lines to match always in the format SRC='nnn' ? Then you could use

grep SRC | cut -d"'" -f2
mobrule
+1  A: 

You can't do it with plain grep. As the man page on my box states: "grep - print lines matching a pattern" grep only prints lines, not part of lines.

I would recommend awk since it can do both the pattern matching and sub-line extracting:

awk -F\' ' /SRC/ {print $2}'
R Samuel Klatchko
Unfortunately I don't have awk on my system...
Derek
+1  A: 

Here is how to do it using sed

grep SRC=\'.*\' | sed 's/SRC=.\(.*\)./\1/'
alexander.egger
A: 

depends on your platform / language.

in Ruby:

string = "SRC = '999'"

string.match(/([0-9]{3})/).to_s.to_i

will return an integer

Nick Gorbikoff
+1  A: 

just sed will do

$ echo SRC='999' | sed '/SRC/s/SRC=//'
999
+1  A: 

You can use the -o option on grep to return only the part of the string that matches the regex:

echo "SRC='999'" | grep -o -E '[0-9]{3}'
Anton Geraschenko