How to remove extra spaces in bash?

后端 未结 10 1751
说谎
说谎 2020-12-01 05:46

How to remove extra spaces in variable HEAD?

HEAD=\"    how to  remove    extra        spaces                     \"

Result:

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 05:53

    Take advantage of the word-splitting effects of not quoting your variable

    $ HEAD="    how to  remove    extra        spaces                     "
    $ set -- $HEAD
    $ HEAD=$*
    $ echo ">>>$HEAD<<<"
    >>>how to remove extra spaces<<<
    

    If you don't want to use the positional paramaters, use an array

    ary=($HEAD)
    HEAD=${ary[@]}
    echo "$HEAD"
    

    One dangerous side-effect of not quoting is that filename expansion will be in play. So turn it off first, and re-enable it after:

    $ set -f
    $ set -- $HEAD
    $ set +f
    

提交回复
热议问题