476

Below is the snippet of a shell script from a larger script. It removes the quotes from the string that is held by a variable. I am doing it using sed, but is it efficient? If not, then what is the efficient way?

#!/bin/sh

opt="\"html\\test\\\""
temp=`echo $opt | sed 's/.\(.*\)/\1/' | sed 's/\(.*\)./\1/'`
echo $temp
3
  • I would suggest using sed "s/^\(\"\)\(.*\)\1\$/\2/g" <<<"$opt". This syntax will remove qoutes only when there is a matching pair.
    – John Smith
    Commented Aug 30, 2017 at 18:33
  • @JohnSmith I also have to automatically escape quotes in a shell script, but I need to do so whether they are matching or not, so I probably will not use that expression you posted.
    – Pysis
    Commented Oct 11, 2017 at 13:46
  • If you found this question while simply wanting to remove all quotes, see this answer: askubuntu.com/a/979964/103498. Commented May 13, 2019 at 18:35

20 Answers 20

597

Use tr to delete ":

 echo "$opt" | tr -d '"'

NOTE: This does not fully answer the question, removes all double quotes, not just leading and trailing. See other answers below.

7
  • 32
    This is not what OP asked for since it also removes all quotes, not just the leading and trailing ones.
    – Lenar Hoyt
    Commented Dec 24, 2015 at 14:51
  • 38
    Although not answering OP explicitly this solves for me because there are only double quotes at beginning and end of "/path/file-name". There are no embedded double quotes. +1 Commented Feb 19, 2017 at 15:55
  • 15
    This solution will be what a lot of people want. In many cases, scripting can easily get the workable data down to a string surrounded by quotes.
    – Shadoninja
    Commented Jun 25, 2018 at 19:27
  • 5
    Elegant and saved me from a lot more trial-error-debug time. Thx.
    – Scott Wade
    Commented Nov 22, 2018 at 0:07
  • 1
    This is what ideally one wants and thats why it has more votes than the accepted answer.
    – apurvc
    Commented Nov 13, 2019 at 17:37
413

There's a simpler and more efficient way, using the native shell prefix/suffix removal feature:

temp="${opt%\"}"
temp="${temp#\"}"
echo "$temp"

${opt%\"} will remove the suffix " (escaped with a backslash to prevent shell interpretation).

${temp#\"} will remove the prefix " (escaped with a backslash to prevent shell interpretation).

Another advantage is that it will remove surrounding quotes only if there are surrounding quotes.

BTW, your solution always removes the first and last character, whatever they may be (of course, I'm sure you know your data, but it's always better to be sure of what you're removing).

Using sed:

echo "$opt" | sed -e 's/^"//' -e 's/"$//'

(Improved version, as indicated by jfgagne, getting rid of echo)

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

So it replaces a leading " with nothing, and a trailing " with nothing too. In the same invocation (there isn't any need to pipe and start another sed. Using -e you can have multiple text processing).

13
  • 17
    You can get rid of the pipe in the sed solution with sed -e 's/^"//' -e 's/"$//' <<< $opt.
    – jfg956
    Commented Mar 17, 2012 at 15:15
  • 1
    This could misbehave it the string doesn't have both a leading and trailing quote character. Any suggestions for handling that gracefully?
    – jsears
    Commented Apr 13, 2016 at 21:37
  • 2
    @jsears Huh? This specifically trims one from the start if there is one, and one from the end if there is one. If you don't want to remove unless both are present; yes, a single sed regex could be used, or the variable substitution could be wrapped in something line case $opt in '"'*'"') ... do it ... ;; esac
    – tripleee
    Commented Oct 7, 2016 at 6:24
  • 5
    You could avoid the multiple expressions by using sed 's/^"\|"$//g'
    – tzrlk
    Commented Oct 18, 2017 at 23:42
  • 1
    You can join multiple sed expressions with a semicolon, like this echo '"foo"' | sed 's/^"//;s/"$//'
    – svaponi
    Commented Jan 7, 2020 at 9:50
219

If you're using jq tool and trying to remove the quotes from the result, the other answers will work, but there's a better way. By using the -r option, you can output the result with no quotes.

$ echo '{"foo": "bar"}' | jq '.foo'
"bar"

$ echo '{"foo": "bar"}' | jq -r '.foo'
bar
3
  • 1
    I'm using jq but please note that it doesn't work if jq is also outputting ASCII output with -a (it's a bug at jq's side) Commented Apr 29, 2020 at 17:13
  • 2
    yq also has -r option: yq -r '.foo' file.yml
    – Hlib Babii
    Commented May 15, 2020 at 17:42
  • echo '{"files":["http://demo.com/1.jpg","http//:demo.com/1.jpg"]}' | jq .files | jq -r 'join(" ")' | xargs wget , -r is very useful when pipe with other tool.
    – chengzi
    Commented Jul 18, 2022 at 17:03
100

There is a straightforward way using xargs:

> echo '"quoted"' | xargs
quoted

xargs uses echo as the default command if no command is provided and strips quotes from the input, see e.g. here. Note, however, that this will work only if the string does not contain additional quotes. In that case it will either fail (uneven number of quotes) or remove all of them.

6
  • 3
    This works, but only for an even number of quotes in a string. If there is an odd number, it generates an error. Commented Oct 16, 2018 at 19:06
  • 2
    The simplest and most elegant! Thanks.
    – rimkashox
    Commented Nov 15, 2021 at 10:09
  • 2
    Worked for me to use via terraform.
    – rimkashox
    Commented Nov 15, 2021 at 10:10
  • 2
    This is the best solution if the expected value only has start/end quotes. Otherwise, xargs will strip all quotes. Commented Mar 22, 2022 at 16:05
  • 1
    This worked absolutely for me. Thank you. Commented May 28, 2022 at 8:46
60

If you came here from AWS CLI --query, try this. --output text

7
  • 2
    Exactly from aws cli --query. Thanks!
    – Gonza
    Commented Jul 21, 2021 at 19:10
  • 8
    For azure cli use --output tsv Commented Aug 26, 2021 at 21:03
  • 4
    Hahaha. Dang this is exactly what I wanted Commented Aug 30, 2021 at 14:21
  • 3
    I came here from AWS CLI, in case you are using the output of CLI with jq, you can use the option -r to read the raw string. For example: aws codeartifact get-authorization-token --domain ${CODEARTIFACT_DOMAIN} | jq -r '.authorizationToken' Commented Aug 26, 2022 at 8:08
  • @JoseRodriguez thats better done with --query IMO
    – Kappacake
    Commented Nov 25, 2022 at 17:50
32

You can do it with only one call to sed:

$ echo "\"html\\test\\\"" | sed 's/^"\(.*\)"$/\1/'
html\test\
1
  • I expected this answer to be at the top!
    – Jerry
    Commented Jul 24 at 11:38
32

The easiest solution in Bash:

$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc

This is called substring expansion (see Gnu Bash Manual and search for ${parameter:offset:length}). In this example it takes the substring from s starting at position 1 and ending at the second last position. This is due to the fact that if length is a negative value it is interpreted as a backwards running offset from the end of parameter.

3
  • 1
    negative lengths supported from bash v4.2 Commented Jun 11, 2020 at 18:29
  • 1
    This is not a solution because it removes the first and last characters indiscriminately. It doesn't remove the first and last quotation marks.
    – Cliff
    Commented Jul 9, 2023 at 7:11
  • +1 although many answers here have pedantically interpreted the question's wording—and brought in a huge amount of complexity to support the general case of quote search—OP's example implies they indeed just want to remove the first and last char . . . this will also be the commonest use-case. And, for that problem, this answer is perfect.
    – geometrian
    Commented Jan 6 at 15:18
30

The shortest way around - try:

echo $opt | sed "s/\"//g"

It actually removes all "s (double quotes) from opt (are there really going to be any more double quotes other than in the beginning and the end though? So it's actually the same thing, and much more brief ;-))

2
  • 7
    If you want to remove all the double quotes, then it's even better to use : "${opt//\"/}". No pipe, no subshell... And beware that if you have spaces in opt, you may loose them. Always quote variables like : echo "$opt"
    – huelbois
    Commented Mar 16, 2012 at 7:35
  • Well, the variable basically reads the path of DocumentRoot from httpd's config file, so I dont think there could be case where a quote character could be possibly there in the string. And this sed is much neater and efficient.... Thanks! Commented Mar 16, 2012 at 8:49
17

Update

A simple and elegant answer from Stripping single and double quotes in a string using bash / standard Linux commands only:

BAR=$(eval echo $BAR) strips quotes from BAR.

=============================================================

Based on hueybois's answer, I came up with this function after much trial and error:

function stripStartAndEndQuotes {
    cmd="temp=\${$1%\\\"}"
    eval echo $cmd
    temp="${temp#\"}"
    eval echo "$1=$temp"
}

If you don't want anything printed out, you can pipe the evals to /dev/null 2>&1.

Usage:

$ BAR="FOO BAR"
$ echo BAR
"FOO BAR"
$ stripStartAndEndQuotes "BAR"
$ echo BAR
FOO BAR
1
  • 5
    Though I really like the simple and elegant, I think it is worth noticing that eval doesn't do just double quote trimmings, but actually evaluates as a line of code. Therefore this technique may yield unexpected results when BAR contains other sequences that may substitute by the shell (e.g. BAR=\'abc\' or BAR=ab\'c or BAR=a\$b, or BAR=a\$(ls *) )
    – MaxP
    Commented Nov 6, 2017 at 13:23
15

I know this is a very old question, but here is another sed variation, which may be useful to someone. Unlike some of the others, it only replaces double quotes at the start or end...

echo "$opt" | sed -r 's/^"|"$//g'

If you need to match single or double quotes, and only strings that are properly quoted. You can use this slightly more complex regex...

echo $opt | sed -E "s|^(['\"])(.*)\1$|\2|g"

This uses backrefences to ensure the quote at the end is the same as at the start.

14
Linux=`cat /etc/os-release | grep "ID" | head -1 | awk -F= '{ print $2 }'`

echo $Linux
Output:
"amzn"

Simplest ways to remove double quotes from variables are

Linux=`echo "$Linux" | tr -d '"'` 
Linux=$(eval echo $Linux)
Linux=`echo ${Linux//\"/}`
Linux=`echo $Linux | xargs`

All provides the Output without double quotes:

echo $Linux

amzn

13

This is the most discrete way without using sed:

x='"fish"'
printf "   quotes: %s\nno quotes:  %s\n" "$x" "${x//\"/}"

Or

echo $x
echo ${x//\"/}

Output:

   quotes: "fish"
no quotes:  fish

I got this from a source.

3
  • 1
    This will remove quotes from within the string as well as those surrounding it.
    – jsears
    Commented Apr 13, 2016 at 21:41
  • 1
    Apart from the commentary, this is identical to @StevenPenny's answer from 2012.
    – tripleee
    Commented Oct 7, 2016 at 6:26
  • Note that this makes use of bash-specific variable substitution and won't work in sh. That said, I think that when using bash this is the best answer. Commented Mar 28, 2022 at 0:45
8

In Bash, you could use the following one-liner:

[[ "${var}" == \"*\" || "${var}" == \'*\' ]] && var="${var:1:-1}"

This will remove surrounding quotes (both single and double) from the string stored in var while keeping quote characters inside the string intact. Also, this won't do anything if there's only a single leading quote or only a single trailing quote or if there are mixed quote characters at start/end.


Wrapped in a function:

#!/usr/bin/env bash

# Strip surrounding quotes from string [$1: variable name]
function strip_quotes() {
    local -n var="$1"
    [[ "${var}" == \"*\" || "${var}" == \'*\' ]] && var="${var:1:-1}"
}

str="'hello world'"
echo "Before: ${str}"
strip_quotes str
echo "After: ${str}"
2
  • a simpler 1 liner... echo $opt | sed -E "s|^(['\"])(.*)\1$|\2|g" Commented Mar 30, 2022 at 4:10
  • 1
    @user1751825: The OP's question was to remove quotes from a string held by a variable, thus you would need to change your one-liner to temp=$(echo "$opt" | sed -E "s|^(['\"])(.*)\1$|\2|g") to achieve that result (also, don't forget to quote $opt). Thus, you would need to use a subshell + pipe to sed. As the OP also asked for an efficient solution, your one-liner is in no way simpler or better than my Bash-only solution.
    – Fonic
    Commented Mar 31, 2022 at 7:10
4
STR='"0.0.0"' ## OR STR="\"0.0.0\""
echo "${STR//\"/}"
## Output: 0.0.0 
2
  • Please add some details and background to your answer for future readers.
    – aggsol
    Commented Sep 21, 2022 at 8:34
  • 1
    This removes quotes anywhere in the string, not just start/end. Commented May 24, 2023 at 7:07
2

My version

strip_quotes() {
    while [[ $# -gt 0 ]]; do
        local value=${!1}
        local len=${#value}
        [[ ${value:0:1} == \" && ${value:$len-1:1} == \" ]] && declare -g $1="${value:1:$len-2}"
        shift
    done
}

The function accepts variable name(s) and strips quotes in place. It only strips a matching pair of leading and trailing quotes. It doesn't check if the trailing quote is escaped (preceded by \ which is not itself escaped).

In my experience, general-purpose string utility functions like this (I have a library of them) are most efficient when manipulating the strings directly, not using any pattern matching and especially not creating any sub-shells, or calling any external tools such as sed, awk or grep.

var1="\"test \\ \" end \""
var2=test
var3=\"test
var4=test\"
echo before:
for i in var{1,2,3,4}; do
    echo $i="${!i}"
done
strip_quotes var{1,2,3,4}
echo
echo after:
for i in var{1,2,3,4}; do
    echo $i="${!i}"
done
2

I use this regular expression, which avoids removing quotes from strings that are not properly quoted, here the different outputs are shown depending on the inputs, only one with begin-end quote was affected:

echo '"only first' | sed 's/^"\(.*\)"$/\1/'

Output: >"only first<

echo 'only last"' | sed 's/^"\(.*\)"$/\1/'

Output: >only last"<

echo '"both"' | sed 's/^"\(.*\)"$/\1/'

Output: >both<

echo '"space after" ' | sed 's/^"\(.*\)"$/\1/'

Output: >"space after" <

echo ' "space before"' | sed 's/^"\(.*\)"$/\1/'

Output: > "space before"<

1

There is another way to do it. Like:

echo ${opt:1:-1}
1
0

If you're here because your terraform output is quoting values, add -raw to remove them. I haven't tracked down the release notes, but at some point around .13, .14, maybe even 1.0.0 there appears to be a change that caused output values to be quoted when they weren't previously.

0

On Mac you may need to enable extended mode on sed.
Example to remove zero or more leading or trailing quotes.

Command:
   echo '""foo""' | sed -E 's/"*([^"]+)"*/\1/'
Output
   foo

To remove quotes from a shell variable.

set yesQuotes='""hello"'
set noQuotes=`echo $yesQuotes | sed -E 's/"*([^"]+)"*/\1/'`

If you want to only remove balanced quotes

set yesQuotes='"hello"'
set noQuotes=`echo $yesQuotes | sed -E 's/"([^"]+)"/\1/'`
 
-2

If you try to remove quotes because the Makefile keeps them, try this:

$(subst $\",,$(YOUR_VARIABLE))

Based on another answer: https://stackoverflow.com/a/10430975/10452175

1
  • $(subst ...) is a make function. The OP hasn't mentioned any Makefile
    – xhienne
    Commented Feb 11, 2021 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.