LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   find word between string (https://www.linuxquestions.org/questions/programming-9/find-word-between-string-655030/)

djcham 07-11-2008 02:19 AM

find word between string
 
Hello all,

I did a search before I posted but did not find what I needed. I am looking to write a sed/awk/cut/tr command that will parse and print out numbers between two unique strings. for instance

number=3243423 random text blah blah yes no number=323432432 fsd jklf sjl number=32432432

basically I have to grab the number after the = sign after every "number=" string without knowing how long the number will be.

Can somebody give some suggestions on how to do this?

I read that you can use

sed -n '/FOO/,/BAR/p' test.txt

but that only works if it is only one line.... and it is inclusive..any help would be great. thank you!

ghostdog74 07-11-2008 02:25 AM

Code:

string="number=3243423 random text blah blah yes no number=323432432 fsd jklf sjl number=32432432"
echo $string | egrep -o "number=[0-9]*" && echo "you do the rest"


Mr. C. 07-11-2008 03:10 AM

Oops, be careful...

Code:

string="number=3243423 random text blah blah yes no number= fsd jklf sjl number=32432432"
$ echo $string | egrep -o "number=[0-9]*"
number=3243423
number=
number=32432432

# Maybe better to force a digit to match
echo $string | egrep -o "number=[0-9][0-9]*"

# Or, another way, removing number=
echo $string | perl -ne 'print "$1\n" while ($_=~/number=(\d+)/g)'


djcham 07-11-2008 03:37 AM

great!! thanks for the help. i think this will solve my problem.

ghostdog74 07-11-2008 03:44 AM

Quote:

Originally Posted by Mr. C. (Post 3210922)
# Maybe better to force a digit to match
echo $string | egrep -o "number=[0-9][0-9]*"

thanks, good catch:)
Code:

echo $string | egrep -o "number=[0-9]+"

Mr. C. 07-11-2008 04:04 AM

It is this both the silly length, and duplication requirement, of the [ ] character classes vs. pcres' \d+, etc. that encourages me to avoid sed/awk much of the time.

ghostdog74 07-11-2008 04:23 AM

later version of sed (-r switch) and gawk have options for extended regular expressions, but not sure about pcre though

Mr. C. 07-11-2008 04:26 AM

Not mine on NetBSD. I'll have to update my /usr/local copy. Thanks, I wasn't aware of that.

ghostdog74 07-11-2008 04:37 AM

no problem.


All times are GMT -5. The time now is 06:57 AM.