How to trim whitespace from a Bash variable?

后端 未结 30 2228
星月不相逢
星月不相逢 2020-11-22 06:09

I have a shell script with this code:

var=`hg st -R \"$path\"`
if [ -n \"$var\" ]; then
    echo $var
fi

But the conditional code always ex

相关标签:
30条回答
  • 2020-11-22 06:42

    Strip one leading and one trailing space

    trim()
    {
        local trimmed="$1"
    
        # Strip leading space.
        trimmed="${trimmed## }"
        # Strip trailing space.
        trimmed="${trimmed%% }"
    
        echo "$trimmed"
    }
    

    For example:

    test1="$(trim " one leading")"
    test2="$(trim "one trailing ")"
    test3="$(trim " one leading and one trailing ")"
    echo "'$test1', '$test2', '$test3'"
    

    Output:

    'one leading', 'one trailing', 'one leading and one trailing'
    

    Strip all leading and trailing spaces

    trim()
    {
        local trimmed="$1"
    
        # Strip leading spaces.
        while [[ $trimmed == ' '* ]]; do
           trimmed="${trimmed## }"
        done
        # Strip trailing spaces.
        while [[ $trimmed == *' ' ]]; do
            trimmed="${trimmed%% }"
        done
    
        echo "$trimmed"
    }
    

    For example:

    test4="$(trim "  two leading")"
    test5="$(trim "two trailing  ")"
    test6="$(trim "  two leading and two trailing  ")"
    echo "'$test4', '$test5', '$test6'"
    

    Output:

    'two leading', 'two trailing', 'two leading and two trailing'
    
    0 讨论(0)
  • 2020-11-22 06:43

    This worked for me:

    text="   trim my edges    "
    
    trimmed=$text
    trimmed=${trimmed##+( )} #Remove longest matching series of spaces from the front
    trimmed=${trimmed%%+( )} #Remove longest matching series of spaces from the back
    
    echo "<$trimmed>" #Adding angle braces just to make it easier to confirm that all spaces are removed
    
    #Result
    <trim my edges>
    

    To put that on fewer lines for the same result:

    text="    trim my edges    "
    trimmed=${${text##+( )}%%+( )}
    
    0 讨论(0)
  • 2020-11-22 06:44
    # Strip leading and trailing white space (new line inclusive).
    trim(){
        [[ "$1" =~ [^[:space:]](.*[^[:space:]])? ]]
        printf "%s" "$BASH_REMATCH"
    }
    

    OR

    # Strip leading white space (new line inclusive).
    ltrim(){
        [[ "$1" =~ [^[:space:]].* ]]
        printf "%s" "$BASH_REMATCH"
    }
    
    # Strip trailing white space (new line inclusive).
    rtrim(){
        [[ "$1" =~ .*[^[:space:]] ]]
        printf "%s" "$BASH_REMATCH"
    }
    
    # Strip leading and trailing white space (new line inclusive).
    trim(){
        printf "%s" "$(rtrim "$(ltrim "$1")")"
    }
    

    OR

    # Strip leading and trailing specified characters.  ex: str=$(trim "$str" $'\n a')
    trim(){
        if [ "$2" ]; then
            trim_chrs="$2"
        else
            trim_chrs="[:space:]"
        fi
    
        [[ "$1" =~ ^["$trim_chrs"]*(.*[^"$trim_chrs"])["$trim_chrs"]*$ ]]
        printf "%s" "${BASH_REMATCH[1]}"
    }
    

    OR

    # Strip leading specified characters.  ex: str=$(ltrim "$str" $'\n a')
    ltrim(){
        if [ "$2" ]; then
            trim_chrs="$2"
        else
            trim_chrs="[:space:]"
        fi
    
        [[ "$1" =~ ^["$trim_chrs"]*(.*[^"$trim_chrs"]) ]]
        printf "%s" "${BASH_REMATCH[1]}"
    }
    
    # Strip trailing specified characters.  ex: str=$(rtrim "$str" $'\n a')
    rtrim(){
        if [ "$2" ]; then
            trim_chrs="$2"
        else
            trim_chrs="[:space:]"
        fi
    
        [[ "$1" =~ ^(.*[^"$trim_chrs"])["$trim_chrs"]*$ ]]
        printf "%s" "${BASH_REMATCH[1]}"
    }
    
    # Strip leading and trailing specified characters.  ex: str=$(trim "$str" $'\n a')
    trim(){
        printf "%s" "$(rtrim "$(ltrim "$1" "$2")" "$2")"
    }
    

    OR

    Building upon moskit's expr soulution...

    # Strip leading and trailing white space (new line inclusive).
    trim(){
        printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)[[:space:]]*$"`"
    }
    

    OR

    # Strip leading white space (new line inclusive).
    ltrim(){
        printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)"`"
    }
    
    # Strip trailing white space (new line inclusive).
    rtrim(){
        printf "%s" "`expr "$1" : "^\(.*[^[:space:]]\)[[:space:]]*$"`"
    }
    
    # Strip leading and trailing white space (new line inclusive).
    trim(){
        printf "%s" "$(rtrim "$(ltrim "$1")")"
    }
    
    0 讨论(0)
  • 2020-11-22 06:47

    You can trim simply with echo:

    foo=" qsdqsd qsdqs q qs   "
    
    # Not trimmed
    echo \'$foo\'
    
    # Trim
    foo=`echo $foo`
    
    # Trimmed
    echo \'$foo\'
    
    0 讨论(0)
  • 2020-11-22 06:48

    Bash has a feature called parameter expansion, which, among other things, allows string replacement based on so-called patterns (patterns resemble regular expressions, but there are fundamental differences and limitations). [flussence's original line: Bash has regular expressions, but they're well-hidden:]

    The following demonstrates how to remove all white space (even from the interior) from a variable value.

    $ var='abc def'
    $ echo "$var"
    abc def
    # Note: flussence's original expression was "${var/ /}", which only replaced the *first* space char., wherever it appeared.
    $ echo -n "${var//[[:space:]]/}"
    abcdef
    
    0 讨论(0)
  • 2020-11-22 06:49

    There is a solution which only uses Bash built-ins called wildcards:

    var="    abc    "
    # remove leading whitespace characters
    var="${var#"${var%%[![:space:]]*}"}"
    # remove trailing whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   
    printf '%s' "===$var==="
    

    Here's the same wrapped in a function:

    trim() {
        local var="$*"
        # remove leading whitespace characters
        var="${var#"${var%%[![:space:]]*}"}"
        # remove trailing whitespace characters
        var="${var%"${var##*[![:space:]]}"}"   
        printf '%s' "$var"
    }
    

    You pass the string to be trimmed in quoted form. e.g.:

    trim "   abc   "
    

    A nice thing about this solution is that it will work with any POSIX-compliant shell.

    Reference

    • Remove leading & trailing whitespace from a Bash variable (original source)
    0 讨论(0)
提交回复
热议问题