How can I trim "/" using shell scripting? How can I trim "/" using shell scripting? shell shell

How can I trim "/" using shell scripting?


Not sure if using sed is ok -- one way to extract out the number could be something like ...

 echo '<span class="val3">MPPTN: 0.9384</span></td>' | sed 's/^[^:]*..//' | sed 's/<.*$//'


The behavior of ${VARIABLE/PATTERN/REPLACEMENT} depends on what shell you're using, and for bash what version. Under ksh, or under recent enough (I think ≥ 4.0) versions of bash, ${finalt/'</span></td>'/} strips that substring as desired. Under older versions of bash, the quoting is rather quirky; you need to write ${finalt/<\/span><\/td>/} (which still works in newer versions).

Since you're stripping a suffix, you can use the ${VARIABLE%PATTERN} or ${VARIABLE%%PATTERN} construct instead. Here, you're removing everything after the first </, i.e. the longest suffix that matches the pattern </*. Similarly, you can strip the leading HTML tags with ${VARIABLE##PATTERN}.

trimmed=${finalt%%</*}; trimmed=${trimmed##*>}

Added benefit: unlike ${…/…/…}, which is specific to bash/ksh/zsh and works slightly differently in all three, ${…#…} and ${…%…} are fully portable. They don't do as much, but here they're sufficient.

Side note: although it didn't cause any problem in this particular instance, you should always put double quotes around variable substitutions, e.g.

echo "${finalt/'</span></td>'/}"

Otherwise the shell will expand wildcards and spaces in the result. The simple rule is that if you don't have a good reason to leave the double quotes out, you put them.


The solution largely depends on what exactly you want to do. If all your strings are going to be of the form <span class="val3">XXXXX: X.XXXX</span></td>, then the simplest solution is

echo $info | cut -c 20-32

If they're of the form <span class="val3">variable length</span></td>, then the simplest solution is

echo $info | sed 's/<span class="val3">//' | sed 's/<\/span><\/td>//'

If it's more general, you can use regexes like in Sai's answer.