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 . _
Asked By: prayagupa

||

You should try with sed instead

sed 's/.//g'
Answered By: fduff

There is no need to execute an external program. bash‘s string manipulation can handle it (also available in ksh93 (where it comes from), zsh and recent versions of mksh, yash and busybox sh (at least)):

$ VERSION='2.3.3'
$ echo "${VERSION//.}"
233

(In those shells’ manuals you can generally find this in the parameter expansion section.)

Answered By: manatwork

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 "$*"

ksh93/zsh/mksh/bash/yash (and busybox ash when built with ASH_BASH_COMPAT)

echo "${VERSION//.}"

zsh

echo $VERSION:gs/./
Answered By: Stéphane Chazelas

In addition to the successful answers already exists. Same thing can be achieved with tr, with the --delete option.

echo "2.3.3" | tr --delete .
echo "2.3.3" | tr -d .       # for MacOS

Which will output: 233

Answered By: daz

Perl

$ VERSION='2.3.3'                                     
$ perl -pe 's/.//g' <<< "$VERSION"           
233

Python

$ VERSION='2.3.3'                                     
$ python -c 'import sys;print sys.argv[1].replace(".","")' "$VERSION"
233

If $VERSION only contains digits and dots, we can do something even shorter:

$ python -c 'print "'$VERSION'".replace(".","")'
233

(beware it’s a code injection vulnerability though if $VERSION may contain any character).

AWK

$ VERSION='2.3.3'
$ awk 'BEGIN{gsub(/./,"",ARGV[1]);print ARGV[1]}' "$VERSION"
233

Or this:

$ awk '{gsub(/./,"")}1' <<< "$VERSION"
233
Answered By: Sergiy Kolodyazhnyy
echo "$VERSION" | tr -cd [:digit:]

That would return only digits, no matter what other characters are present

Answered By: user2796674
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.