1
var="<string> 1.11 </string>"

I want to get rid of <string> and </string>

How can I do it?

For now i got this:

var=${var:9:4}

1.11
2

You could use sed for string manipulation:

echo '$var = <string> 1.11 </string>' | sed -r 's/<string>(.*)<\/string>/\1/g'

returns

$var =  1.11 

Explanation of the sed construct:

sed -r                       # call sed with regex-option (-r)
  's/                        # begin of regex (s means "replace, / is the seperator)
     <string>(.*)<\/string>  # construct that should be replaced (the / has to be escaped with \ here)
   /                         # seperator
     \1                      # replacement string (\1 means "whatever is matched between the () before")
   /g'                       # apply replacement globally (in case it occurs multiple times in the string)
1

I'm using another solution:

echo '$var = <string> 1.11 </string>' | awk -F'> | <' '{print $1,$3}'

What I did was defining > and < as delimiters and printing certain fields between the delimiters.

  • My pleasure, really :) – Yaron Jun 20 '16 at 7:15
0

Bash has also its own regular expressions. However, they are not so powerful as in sed. The following code does the magic without calling external programs:

var="<string> 1.11 </string>"

first=${var#<*>}
second=${first%<*>}

#echo $first
echo $second

I tried to do it in one step too, but didn't succeed because bash regular expressions do not support non-greedy regular expressions. I tried something like this:

${var//<*>}

The code removes everything from the first < to the last >. :(

I am sure it can be done in one step with

${string/substring/replacement}
${string//substring/replacement}

but I don't have time to experiment right now. For details take a look here: http://www.tldp.org/LDP/abs/html/string-manipulation.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.