wawek
wawek

Reputation: 1597

Grab string from between 2 words but with the beginning

I want to grab a string with sed. Let's say I got string aabbcc and I want to find what is between aa and cc. I use sed like this:

sed -n '/aa/,/cc/p' 

and it's fine but I want to get something like aabb so I want sed to return string between beginning and ending but including beginning.

How can I do that?

EDIT

Ok let me be more specific. My file where I look for texts looks like this:

aa bbbbbbbbbbbbbb  
bbbbbbbbbbbbbbbbb  
bbbbbbbbbbbbbbbbb  
cc

Upvotes: 0

Views: 84

Answers (3)

anubhava
anubhava

Reputation: 784928

Use sed like this:

d='aabbcc'
s='aa'
e='cc'
sed "s/^\(${a}.*\)${e}$/\1/" <<< "$d"
aabb

EDIT: Based on edited question, use this command:

sed -n '/aa/,/cc/{/cc/!p;}' file
aa bbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbb

Upvotes: 1

konsolebox
konsolebox

Reputation: 75458

For

Let's say I got string aabbcc and I want to find what is between aa and cc.

echo "aabbcc" | sed -r 's/aa(.*)cc/\1/'

Output:

bb

Upvotes: 0

Patrick B.
Patrick B.

Reputation: 12333

From the current state of your question I gather this is a possible answer:

sed -n 's/\(^.*bb\).*/\1/p'

used like this:

echo "aabbcc" | sed -n 's/\(^.*bb\).*/\1/p'

prints

aabb

Upvotes: 0

Related Questions