Bash: How to trim a string or a variable

Sometimes you are looking for a simple way to get rid of leading or tailing spaces in a string or variable. Here’s a function I usually use in my bash scripts:

function trim() {
trvar=$1
trvar="${trvar#"${trvar%%[![:space:]]*}"}"
trvar="${trvar%"${trvar##*[![:space:]]}"}"
echo -n "$trvar"
}

… where the first line is responsible for leading and the second line for trailing spaces.

To delete all spaces in a string, you can use:
# echo " this is an example " | tr -d [[:space:]]

About Juergen Caris

I am 54yo, MSc(Dist) and BSc in Computer Science, German and working as a Senior Server Engineer for the NHS Lothian. I am responsible for the patient management system, called TrakCare. I am a UNIX/Linux guy, working in this sector for more than 20 years now. I am also interested in robotics, microprocessors, system monitoring, Home automation and programming.
This entry was posted in Bash, Linux, Uncategorized. Bookmark the permalink.

One Response to Bash: How to trim a string or a variable

  1. Anonymous says:

    There are some interesting points in time in this article but I don’t know if I see all of them center to heart.There is some validity but I will take hold opinion until I look into it further.Good article , thanks and we want more! Added to FeedBurner as well

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>