How to trim whitespace from a Bash variable?

后端 未结 30 2161
星月不相逢
星月不相逢 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: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")")"
    }
    

提交回复
热议问题