This tutorial will help you to remove the start and ending double quotes from strings in a shell script. Where the string is stored in a variable.

Advertisement

Remove Double Quote from a String

The sed command line utility helps to easily handle this. A single-line sed command can remove quotes from the start and end of the string.

sed -e 's/^"//' -e 's/"$//' 

The above sed command executes two expressions against the variable value.

  • The first expression 's/^"//' will remove the starting quote from the string.
  • Second expression 's/"$//' will remove the ending quote from the string.

Shell Script Remove Double Quote from String

Remove Double Quote and Store Output

The result will be printed on the terminal. You can also save the result to a variable and or redirect output to a file.

The below commands will help you to remove double quotes and store output to the same or different variable.

var2=`sed -e 's/^"//' -e 's/"$//'    #Save in another variable 
var1=`sed -e 's/^"//' -e 's/"$//'    #Save in same variable 

Even you can store the result in a file. like:

sed -e 's/^"//' -e 's/"$//'  out_var.txt 

Conclusion

This tutorial helped you to remove the start and ending double quotes from a string stored in a variable using shell script.

Share.

4 Comments

  1. Re-sent due to typo 🙁
    (missing “$”)

    If you are using bash there is a far more efficient solution, without the need to invoke an external program (sed):
    var2=”{var1%\”}”; var2=”${var2#\”}”
    If you definitely know from the context that *both* double quotes are really present within var1, then there is an even more efficient solution:
    var2=”${var1:1:-1}”
    Not sure in case of other shells.

    Warning in case you copy+paste the command lines from this comment:
    The forum software seems to capriciously change ordinary double quotes into typographical ones!

    • Heck, this wasn’t a typo!
      Dear Moderator,
      in fact, your forum software swallowed the missing “$” AGAIN !
      I’m afraid, your software is getting confused by the double quotes when trying to convert then to the allegedly “correct” typographical ones. (I’m hating such software highhandedness 😉 )
      Please add the “$” before the first left brace in the first command line in my comment.
      Thank you

  2. If you are using bash there is a far more efficient solution, without the need to invoke an external program (sed):
    var2=”{var1%\”}”; var2=”${var2#\”}”
    If you definitely know from the context that *both* double quotes are really present within var1, then there is an even more efficient solution:
    var2=”${var1:1:-1}”
    Not sure in case of other shells.

Leave A Reply


Exit mobile version