How to remove extra spaces in bash?

后端 未结 10 1731
说谎
说谎 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:57

    Whitespace can take the form of both spaces and tabs. Although they are non-printing characters and unseen to us, sed and other tools see them as different forms of whitespace and only operate on what you ask for. ie, if you tell sed to delete x number of spaces, it will do this, but the expression will not match tabs. The inverse is true- supply a tab to sed and it will not match spaces, even if the number of them is equal to those in a tab.

    A more extensible solution that will work for removing either/both additional space in the form of spaces and tabs (I've tested mixing both in your specimen variable) is:

    echo $HEAD | sed 's/^[[:blank:]]*//g'
    

    or we can tighten-up @Frontear 's excellent suggestion of using xargs without the tr:

    echo $HEAD | xargs
    

    However, note that xargs would also remove newlines. So if you were to cat a file and pipe it to xargs, all the extra space- including newlines- are removed and everything put on the same line ;-).

    Both of the foregoing achieved your desired result in my testing.

提交回复
热议问题