Replace substring from a string variable

Hi,

Wish to remove "DR-" from the string variable (var).

 var="DR-SERVER1"
 var=`echo $var | sed -e 's/DR-//g'`
 echo "$var"

Expected Output:

However, I get the below error:

Can you please suggest.

That error message comes from somewhere else in your script, not from these three lines..

Thank you for pointing out. i will close this thread.

Hi mohtashims,
As you have been told many times before, it ALWAYS helps if you tell us what operating system and shell you're using when you start a thread.

Even though the diagnostic messages you reported were not coming from the code you showed us, you should still consider updating that code. Firing up a sub-shell to perform a command substitution, an echo , and sed to do the job of a simple parameter substitution is a great way to slow down your script and make your system less responsive to any other task running on your system at the same time.

Unless you're using a pure Bourne shell from the 1970's, please consider changing:

 var="DR-SERVER1"
 var=`echo $var | sed -e 's/DR-//g'`
 echo "$var"

to:

 var="DR-SERVER1"
 var=${var#DR-}
 echo "$var"
1 Like

Mohtashims,
This is at least the second thread in which you have used constructs like

var1=xyz123
var2=`echo $var1 | command1 | command2`

to modify variables only to have others show how parameter expansions can do the same thing. Please read the manual page for your shell, e.g.

man bash
man sh
man dash

and in the man page browser, type

/  parameter expansion

That is slash followed by two spaces followed by "parameter expansion". This should take you to the section on parameter expansion, which will show how you can manipulate the contents of a shell variable within the shell you are scripting in. By using these constructs you will produce faster, cleaner code, and perhaps reduce some of the problems these other constructs introduce.

Who knows? Maybe in the near future you will be helping other members of this forum with their shell-variable manipulation.

Andrew

2 Likes