Shell script - remove first and last quote (") from a variable

后端 未结 15 1727
刺人心
刺人心 2020-11-30 16:47

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?

相关标签:
15条回答
  • 2020-11-30 17:17

    You can do it with only one call to sed:

    $ echo "\"html\\test\\\"" | sed 's/^"\(.*\)"$/\1/'
    html\test\
    
    0 讨论(0)
  • 2020-11-30 17:19

    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).

    0 讨论(0)
  • 2020-11-30 17:20

    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.

    0 讨论(0)
  • 2020-11-30 17:20

    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
    
    0 讨论(0)
  • 2020-11-30 17:23

    If you're using jq 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
    
    0 讨论(0)
  • 2020-11-30 17:25

    This will remove all double quotes.

    echo "${opt//\"}"
    
    0 讨论(0)
提交回复
热议问题