Blog

03/06/2019

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



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 nixCraft 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.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...