1

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 Answers 3

5

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]+'
Sign up to request clarification or add additional context in comments.

9 Comments

<<< "aaa bbb ccc ddd eee" | grep syntax did not work on my system (ubuntu, bash4).
@anishsane: my mistake, it was supposed to be <<<"..." grep (no pipe), but your edit is also fine.
@Thor just noticed that you had the look-around solution. +1 yours, removing mine... well I used .*? non-greedy.. but this is not explained very clearly by OP. Your answer is good!
Yeah, sorry, i'll put the situation: I want to make a curl to get my ip address from checkip.dyndns.org, but the string from there is "Current IP Address: xxx.xxx.xxx.xxx". I want to extract only the ip number from that string, so i think that sed should be the best option? (Actually, im not expert with unix, so, any advice is welcome :)) That's it! :)
@user2266881: the way to show appreciation around here is to upvote useful answers and accept the best one (if it solves your issue).
|
1

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/'

Comments

0

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

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

1 Comment

Interesting - I see this and one other answer that both group the REs before and after the target RE even though they don't use them for anything. I wonder why...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.