How to trim whitespace from a Bash variable?

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

    Assignments ignore leading and trailing whitespace and as such can be used to trim:

    $ var=`echo '   hello'`; echo $var
    hello
    
    0 讨论(0)
  • 2020-11-22 06:39

    I found that I needed to add some code from a messy sdiff output in order to clean it up:

    sdiff -s column1.txt column2.txt | grep -F '<' | cut -f1 -d"<" > c12diff.txt 
    sed -n 1'p' c12diff.txt | sed 's/ *$//g' | tr -d '\n' | tr -d '\t'
    

    This removes the trailing spaces and other invisible characters.

    0 讨论(0)
  • 2020-11-22 06:40
    var='   a b c   '
    trimmed=$(echo $var)
    
    0 讨论(0)
  • 2020-11-22 06:40

    This will remove all the whitespaces from your String,

     VAR2="${VAR2//[[:space:]]/}"
    

    / replaces the first occurrence and // all occurrences of whitespaces in the string. I.e. all white spaces get replaced by – nothing

    0 讨论(0)
  • 2020-11-22 06:41

    You can delete newlines with tr:

    var=`hg st -R "$path" | tr -d '\n'`
    if [ -n $var ]; then
        echo $var
    done
    
    0 讨论(0)
  • 2020-11-22 06:41

    Removing spaces to one space:

    (text) | fmt -su
    
    0 讨论(0)
提交回复
热议问题