Bash Shell: Remove (Trim) White Spaces From String / Variable

17

I have a bash variable as follows:

output="$(awk -F',' '/Name/ {print $9}' input.file)"

How do trim leading and trailing whitespace from bash variable called $output? How do I trim trailing whitespace from $output?

You can use sed, awk, cut, tr, and other utilities to remove whitespace from $output.

Sample data

Define a variable called ouput:

output=" This is a test"

Use echo statement to display $output:

echo "=${output}="
Sample outputs:

=    This is a test=

sed Example

The syntax is:

echo "${output}" | sed -e 's/^[ t]*//'

Sample outputs:

This is a test

Bash Example

The syntax is to remove leading whitespaces:

${var##*( )}

For example:

# Just remove leading whiltespace
#turn it on
shopt -s extglob
 
output="    This is a test"
output="${output##*( )}"
echo "=${output}="
 
# turn it off
shopt -u extglob

Sample outputs:

=This is a test=

To trim leading and trailing whitespace using bash, try:

#turn it on
shopt -s extglob
output="    This is a test    "
 
### Trim leading whitespaces ###
output="${output##*( )}"
 
### trim trailing whitespaces  ##
output="${output%%*( )}
echo "=${output}="
 
# turn it off
shopt -u extglob

Sample outputs:

=This is a test=

awk Example

The syntax is:

output="    This is a test    "
echo "=${output}="
 
## Use awk to trim leading and trailing whitespace
echo "${output}" | awk '{gsub(/^ +| +$/,"")} {print "=" $0 "="}'

Sample outputs:

=This is a test=

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Comments are closed, but trackbacks and pingbacks are open.