search & replace in variable

Can I use search & replace in any variable?

Suppose I have one variable named var1 which holds value "abcabc" I need to search 'a' in var1 and want to replace with 'x' like 'xbcxbc'. Is it possible? Can you provide me an example?

Malay

If you are using sh read the man pages of sh

Under the Parameter Expansion section

       ${parameter/pattern/string}
       ${parameter//pattern/string}
              The pattern is expanded to produce a pattern just as in pathname
              expansion.  Parameter is expanded and the longest match of  pat-
              tern  against  its  value is replaced with string.  In the first
              form, only the first match is replaced.  The second form  causes
              all  matches  of pattern to be replaced with string.  If pattern
              begins with #, it must match at the beginning  of  the  expanded
              value  of parameter.  If pattern begins with %, it must match at
              the end of the expanded value of parameter.  If string is  null,
              matches  of  pattern are deleted and the / following pattern may
              be omitted.  If parameter is @ or *, the substitution  operation
              is  applied to each positional parameter in turn, and the expan-
              sion is the resultant list.  If parameter is an  array  variable
              subscripted  with  @ or *, the substitution operation is applied
              to each member of the array in turn, and the  expansion  is  the
              resultant list.

That would translate to a construct like this

${var1//a/x}

I couldnt find any similiar shell builtin for ksh.

There are a bunch of solutions for something similiar in this thread Find and replace the value in a variable

vino

Why can't you echo the variable to sed and search and replace

echo "abcabc" | sed 's/a/x/g'

There is nothing wrong in doing that.

But why invoke an external program (sed, in this case) when the shell allows you to do the same thing.