2

I want to remove white spaces (\t, \n, \r, space) form the beginning and the end of a string if they exist

How to do that?

Is it possibe to that only with expressions like ${str#*}?

Trevor
  • 1,111
  • 2
  • 18
  • 30
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

3 Answers3

3

If you're using bash (which your idea of ${str#} seems to suggest), then you can use this:

echo "${str##[[:space:]]}" # trim all initial whitespace characters
echo "${str%%[[:space:]]}" # trim all trailing whitespace characters
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

You can say

sed -e 's/^[ \t\r\n]*//' -e 's/[ \t\r\n]*$//' <<< "string"
#         ^^^^^^^^^^^           ^^^^^^^^^^
#         beginning            end of string

Or use \s to match tab and space if it is supported by your sed version.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    `[[:space:]]` should work in any POSIX-compliant version of sed. – Tom Fenech Dec 09 '15 at 11:30
  • 1
    @TomFenech yes, it should, thanks. I did not use it because the user is tagging with the tag `ash` and I remember from his previous questions that he works with old systems, so I cannot rely on anything : ) – fedorqui Dec 09 '15 at 11:32
0

If you can use sed then:

echo "${str}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
P.P
  • 117,907
  • 20
  • 175
  • 238