MOHAMED
MOHAMED

Reputation: 43558

How to remove white spaces (\t, \n, \r, space) form the beginning and the end of a string in shell?

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#*}?

Upvotes: 2

Views: 888

Answers (3)

Tom Fenech
Tom Fenech

Reputation: 74685

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

Upvotes: 3

P.P
P.P

Reputation: 121417

If you can use sed then:

echo "${str}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'

Upvotes: 0

fedorqui
fedorqui

Reputation: 290175

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.

Upvotes: 0

Related Questions