How to Remove Extra White Space From a String in Bash Scripting

remove-white-space
remove-white-space

Sometimes it’s useful for every system administrator or a shell programmer to remove white space from a string or a line of strings for their scripting purposes. Here I have took various scenarios by including extra white space at the beginning of the line, in between the strings and at the end of the line. So, let’s see how to remove leading, trailing white space from the line of strings along with white space in between the strings.

remove-white-space

remove-white-space

Remove a single space from a String:

Let’s take an example of a random string with extra white spaces at the beginning, end and in between the stings.

string="  This is a string with  leading and trailing  spaces and spaces   in between  "
echo ${string//[[:blank:]]/}
echo -e "${string}" | tr -d '[:space:]'

Remove Leading White Space from a String:

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

Remove Tailing White Space from a String

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

Remove both Leading and Trailing White Space from a String

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

Remove extra spaces in the string along with leading and trailing spaces

var=`echo $string`
echo "$var"

Now, let’s see how these commands will run on a shell environment, for that I have written a script including all of these cases separated by a newline(echo). First just go through the script and then look at the output once after understanding the logic.

#! /bin/bash

string=" This is a String with leading and trailing spaces and spaces in between "
echo "Remove All Spaces in a String:"
echo ${string//[[:blank:]]/}
echo
echo "Remove All Whitespace in a string:"
echo -e "${string}" | tr -d '[:space:]'
echo
echo "Remove Leading Whitespace only:"
echo -e "${string}" | sed -e 's/^[[:space:]]*//'
echo
echo "Remove trailing Whitespace only:"
echo -e "${string}" | sed -e 's/[[:space:]]*$//'
echo
echo "Remove both Leading and trailing Whitespace"
echo -e "${string}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
echo
echo "Remove extra spaces in the string along with leading and trailing spaces:"
echo $string | xargs
echo
var=`echo $string`
echo
echo "$var"
Remove white space from a string bash

Remove white space from a string bash

If you have any queries on this, please drop a comment below so that I would be able to help you on that.

Be the first to comment on "How to Remove Extra White Space From a String in Bash Scripting"

Leave a comment

Your email address will not be published.


*