How to remove extra spaces in bash?

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

How to remove extra spaces in variable HEAD?

HEAD=\"    how to  remove    extra        spaces                     \"

Result:

10条回答
  •  春和景丽
    2020-12-01 06:03

    Here's how I would do it with sed:

    string='    how to  remove    extra        spaces                     '
    echo "$string" | sed -e 's/  */ /g' -e 's/^ *\(.*\) *$/\1/'
    
    => how to remove extra spaces   # (no spaces at beginning or end)
    

    The first sed expression replaces any groups of more than 1 space with a single space, and the second expression removes any trailing or leading spaces.

提交回复
热议问题