How to remove extra spaces in bash?

后端 未结 10 1710
说谎
说谎 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.

    0 讨论(0)
  • 2020-12-01 06:11

    Using awk:

    $ echo "$HEAD" | awk '$1=$1'
    how to remove extra spaces
    
    0 讨论(0)
  • 2020-12-01 06:11

    I would make use of tr to remove the extra spaces, and xargs to trim the back and front.

    TEXT="     This          is  some                             text   "
    echo $(echo $TEXT | tr -s " " | xargs)
    
    # [...]$ This is some text
    
    0 讨论(0)
  • 2020-12-01 06:12

    Try this one:

    echo '    how to  remove    extra        spaces                     ' | sed 's/^ *//g' | sed 's/$ *//g' | sed 's/   */ /g'
    

    or

    HEAD="    how to  remove    extra        spaces                     "
    HEAD=$(echo "$HEAD" | sed 's/^ *//g' | sed 's/$ *//g' | sed 's/   */ /g')
    
    0 讨论(0)
提交回复
热议问题