Replacing * by < in a variable in bash script

Viewed 41

I have a variable var="TAG: *** Reason:Circumvention *** SSC" I have to put this variable between double quotes otherwise it changes the *** into the files on my homedirectory

$ var="TAG: *** Reason:Circumvention *** SSC"
$ echo $var
TAG: sqlnet.log test.sh tst.sh Reason:Circumvention sqlnet.log test.sh tst.sh SSC
$ echo "$var"
TAG: *** Reason:Circumvention *** SSC

Now I want to change all * into another character (e.g. <) and put it into a new variable (so I don't have to put it into double quotes anymore) but it seems it replaces the whole variable by <. How can I avoid this ?

$ echo "$var"
TAG: *** Reason:Circumvention *** SSC
$ newvar="${var//*/<}"
$ echo $newvar
<
1 Answers

To quote the bash manual under Pattern Matching

Pattern Matching

   Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern.   A  backslash
   escapes the following character; the escaping backslash is discarded when matching.  The special pattern characters must be quoted if they are to be matched literally.

   The special pattern characters have the following meanings:

          *      Matches any string, including the null string.  When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a
                 single pattern will match all files and zero or more directories and subdirectories.  If followed by a /, two adjacent *s will match only directories and subdirec-
                 tories.

Either escape the glob * or put it inside single quotes.

var="TAG: *** Reason:Circumvention *** SSC"
newvar=${var//\*/<}          
echo "$newvar"

Or

newvar=${var//'*'/<}
  • The glob * will match all the character/strings from start to the end, and replace it with whatever you have in the Parameter Expansion replacement, in this case the < sign.
Related