1
votes

i need to get the text between two words or text segments in a string.

I've searched and tried EVERTYHING with sed, and can't get it to work :S

I have a string like "aaa bbb ccc ddd eee" and i want to extract the text between, let's say, bbb and ddd.

3

3 Answers

4
votes

Assuming bbb doesn't occur after the text you are interested in, and the reverse constraint for ddd, you can do it like this:

 sed 's/^.*bbb //; s/ddd.*$//' <<< "aaa bbb ccc ddd eee" 

Output:

ccc

sed is probably not the best tool for this, maybe you could explain a bit more about what you are trying to do? For example you may want to use positive lookbehind and lookahead:

grep -oP '(?<=bbb ).*?(?=ddd)' <<< "aaa bbb ccc ddd eee" 

Output:

ccc

Edit

According to comments the OP wants to extract the ip address from checkip.dyndns.org. A generic and more portable way to do that is with grep -o, e.g.:

curl -s http://checkip.dyndns.org/ | grep -oE '([0-9]+.){3}[0-9]+'
1
votes

You could use sed groupings. The three pairs of parentheses denote three groupings. \2 on the output side is the content of the second grouping

sed 's/\(^.*bbb\)\(.*\)\(ddd.*$\)/\2/'
0
votes

Assuming you don't want the spaces around the output text between bbb and ddd

sed 's|^\(.*bbb *\)\(.*\)\( *ddd.*\)$|\2|g'