How to trim whitespace from a Bash variable?

后端 未结 30 2245
星月不相逢
星月不相逢 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条回答
  •  -上瘾入骨i
    2020-11-22 06:38

    Here's a trim() function that trims and normalizes whitespace

    #!/bin/bash
    function trim {
        echo $*
    }
    
    echo "'$(trim "  one   two    three  ")'"
    # 'one two three'
    

    And another variant that uses regular expressions.

    #!/bin/bash
    function trim {
        local trimmed="$@"
        if [[ "$trimmed" =~ " *([^ ].*[^ ]) *" ]]
        then 
            trimmed=${BASH_REMATCH[1]}
        fi
        echo "$trimmed"
    }
    
    echo "'$(trim "  one   two    three  ")'"
    # 'one   two    three'
    

提交回复
热议问题