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

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux/Unix+Bash/Ksh
Est. reading time N/A
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=

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 16 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
16 comments… add one
  • xof Jan 18, 2013 @ 8:43

    check the title it says “While” Spaces

  • Eugéne Jan 23, 2013 @ 12:37

    I tend to just stick to sed for this typeof thing:

    jsoap@nixbox:~$ output=" This is a test  "
    jsoap@nixbox:~$ echo "=${output}="
    = This is a test  =
    jsoap@nixbox:~$ output=$( echo "${output}"| sed -e 's/^ *//' -e 's/ *$//' );
    jsoap@nixbox:~$ echo "=${output}="
    =This is a test=
    jsoap@nixbox:~$ 
    

    Since a lot of my work needs to live on BSD, AIX and Solaris, as well as on Linux, I tend to script very defensively and portably. It has saved my butt more times than bears mentioning…

  • Shantanu Gadgil Feb 16, 2013 @ 10:34

    If the content is a single line of text, why not just use echo ?

    $VAR=$(echo $VAR)
    

    notice there are no double-quotes for the inner $VAR

    • Shantanu Gadgil Feb 21, 2013 @ 9:26

      … slight error …. it should be

      VAR=$(echo $VAR)
      
  • Keith Feb 22, 2013 @ 18:22

    This is the BEST site in the world. I can’t tell you how many times I have wound up here to find the answer to my question or problem. Great resource, thanks!!!

  • Krishna Chappidi Feb 26, 2013 @ 15:41

    Hello..
    Could you please help me out….
    Here is my scenario:
    1. i am listing some of the processes which are active and sending the output to temp.txt.
    2. i got many processes, if i want to kill/doing some thing with any inactive process it should throw an error message.
    3. how do i work with pattern matching commands in temp.txt?
    Please suggest me the better answer..

  • Larry Helms Feb 27, 2013 @ 1:50
    m=$( echo "${output}" | sed -e "s/^\ *//g" -e "s/\ *$//g")
    
    echo "=${m}="
    
    =This is a test=
    
  • Leszek Feb 4, 2014 @ 8:11

    Very helpful. Thanks.

  • Eric Sep 7, 2014 @ 22:40

    I’m not sure why the examples use extglob in bash. It’s completely unneeded when using the ## or %% operators. ${VAR%% } will remove trailing whitespace, as long as it’s not mixed tabs and spaces.

  • Riccardo Jan 16, 2015 @ 9:12

    echo ” blah ” | awk ‘{print $NF }’

  • Shark Apr 9, 2015 @ 7:16

    You can also pipe to tr this:

    shark@debian:~$ echo "=    This is a test="|tr -s " "
    = This is a test=
  • parinay May 28, 2015 @ 13:17
    "${output##*( )}" output="${output%%*( )} 

    Is this bash version specific ? Any reference for the same ?

    Thanks

  • Vijay P Dec 10, 2015 @ 7:24

    This is great useful site!!
    Thanks!

  • apexik Aug 5, 2016 @ 22:10

    I extend the ‘Bash Example’ as follows:
    useful for whitespaces the ${var##*(tab|space)} form, where the tab is itself, and the space is also itself, it look like ${var##*( | )} or ${var%%( | )} typed in editor.

    Thanks, and best regards, Miki

  • sparky Sep 7, 2016 @ 16:32

    awk ‘{$1=$1};1’

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum