How to trim whitespace from a Bash variable?

后端 未结 30 2667
星月不相逢
星月不相逢 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:34

    I would simply use sed:

    function trim
    {
        echo "$1" | sed -n '1h;1!H;${;g;s/^[ \t]*//g;s/[ \t]*$//g;p;}'
    }
    

    a) Example of usage on single-line string

    string='    wordA wordB  wordC   wordD    '
    trimmed=$( trim "$string" )
    
    echo "GIVEN STRING: |$string|"
    echo "TRIMMED STRING: |$trimmed|"
    

    Output:

    GIVEN STRING: |    wordA wordB  wordC   wordD    |
    TRIMMED STRING: |wordA wordB  wordC   wordD|
    

    b) Example of usage on multi-line string

    string='    wordA
       >wordB<
    wordC    '
    trimmed=$( trim "$string" )
    
    echo -e "GIVEN STRING: |$string|\n"
    echo "TRIMMED STRING: |$trimmed|"
    

    Output:

    GIVEN STRING: |    wordAA
       >wordB<
    wordC    |
    
    TRIMMED STRING: |wordAA
       >wordB<
    wordC|
    

    c) Final note:
    If you don't like to use a function, for single-line string you can simply use a "easier to remember" command like:

    echo "$string" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
    

    Example:

    echo "   wordA wordB wordC   " | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
    

    Output:

    wordA wordB wordC
    

    Using the above on multi-line strings will work as well, but please note that it will cut any trailing/leading internal multiple space as well, as GuruM noticed in the comments

    string='    wordAA
        >four spaces before<
     >one space before<    '
    echo "$string" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
    

    Output:

    wordAA
    >four spaces before<
    >one space before<
    

    So if you do mind to keep those spaces, please use the function at the beginning of my answer!

    d) EXPLANATION of the sed syntax "find and replace" on multi-line strings used inside the function trim:

    sed -n '
    # If the first line, copy the pattern to the hold buffer
    1h
    # If not the first line, then append the pattern to the hold buffer
    1!H
    # If the last line then ...
    $ {
        # Copy from the hold to the pattern buffer
        g
        # Do the search and replace
        s/^[ \t]*//g
        s/[ \t]*$//g
        # print
        p
    }'
    

提交回复
热议问题