jueves, 10 de diciembre de 2015

remove particular characters from a variable using bash


I want to parse a variable (in my case it's development kit version) to make it dot(.) free. If version='2.3.3', desired output is 233.
I tried as below, but it requires . to be replaced with another character giving me 2_3_3. It would have been fine if tr . '' would have worked.
  1 VERSION='2.3.3' 
  2 echo "2.3.3" | tr . _
shareimprove this question
2 
No, it doesn't require: echo "2.3.3" | tr -d .. – manatwork Dec 12 '13 at 14:59 
   
@manatwork Great, that works. You can post it as answer. Thanks – Prayag Upd Dec 12 '13 at 15:04
   
Lot of good answers. But if I can second-guess the objective, be warned about 2.11.3 and 2.1.13... ;-) Consider adding padding zeroes to numbers. – Rmano Dec 12 '13 at 16:06 
   
@Rmano You mean something like VERSION='2.30.3100'? No matter what just .'s are removed with all of the answers here. – Prayag Upd Dec 12 '13 at 16:13 
   
@PrayagUpd --- I simply meant that if you will use the number after the conversion for comparisons (as to say if "is this version newer or the same") you should take care of cases like 2.11.3 and 2.1.13 --- they seems the same after dot removal, but clearly 2.11.3 is newer. Also, 2.11.3 is newer than 2.1.14, but comparing 2113 and 2114 will lead to the wrong answer. I remember a bug somewhere for this... – RmanoDec 12 '13 at 16:19

3 Answers

up vote19down voteaccepted
There is no need to execute an external program. bash's string manipulation can handle it (also available in ksh (where it comes from) and zsh):
VERSION='2.3.3'
echo "${VERSION//.}"
(In those shells' manuals you can find this in the parameter expansion section.)
shareimprove this answer
By chronological order:

tr/sed

echo "$VERSION" | tr -d .
echo "$VERSION" | sed 's/\.//g'

csh/tcsh

echo $VERSION:as/.//

POSIX shells:

set -f
IFS=.
set -- $VERSION
IFS=
echo "$*"

ksh/zsh/bash

echo "${VERSION//.}"

zsh

echo $VERSION:gs/./
shareimprove this answer
you should try with sed instead
sed 's/\.//g'
shareimprove this answer

No hay comentarios:

Publicar un comentario