0

I cannot get this to work. I only want to get the string between 2 others in bash. Like this:

FOUND=$(echo "If show <start>THIS WORK<end> then it work" | **the magic**)
echo $FOUND

It seems so simple...

2
  • Do you have <start> and <end> in your string? Or thats for us as reference? If not then what is your actual string and desired output? A bit more information would certainly help! Commented Dec 19, 2011 at 23:44
  • @JaypalSingh the <start> and <end> is a reference. Can be any text :) $FOUND have only to show "THIS WORK" Commented Jan 18, 2012 at 19:48

3 Answers 3

5
sed -n 's/.*<start>\(.*\)<end>.*/\1/p'
Sign up to request clarification or add additional context in comments.

Comments

3

This can be done in bash without any external commands such as awk and sed. When doing a regex match in bash, the results of the match are put into a special array called BASH_REMATCH. The second element of this array contains the match from the first capture group.

data="If show <start>THIS WORK<end> then it work"
regex="<start>(.*)<end>"
[[ $data =~ $regex ]] && found="${BASH_REMATCH[1]}"
echo $found

This can also be done using perl regex in grep (GNU specific):

found=$(grep -Po '(?<=<start>).*(?=<end>)' <<< "If show <start>THIS WORK<end> then it work")
echo "$found"

Comments

0

If you have < start > and < end > in your string then this will work. Set the FS to < and >.

[jaypal:~/Temp] FOUND=$(echo "If show <start>THIS WORK<end> then it work" | 
awk -v FS="[<>]" '{print $3}')
[jaypal:~/Temp] echo $FOUND
THIS WORK

Comments

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.