Bash Script Replace Empty Spaces String

How do I remove all spaces from string using shell scripts? I’ve var=”This is a test”, and I’d like to remove all spaces.

You can sed stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is ‘sed’s ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

Remove All Spaces

echo "This     is    a   test" | sed 's/ //g'
var="This     is    a   test" 
echo $var | sed 's/ //g'

Replace All Spaces With * Symbol

echo "This     is    a   test" | sed 's/ /*/g'
var="This     is    a   test" 
echo $var | sed 's/ /*/g'

Replace All Spaces With Bash

Bash shell supports a find and replace via substitution for string manipulation operation. The syntax is as follows:


Replace all matches of Pattern with Replacement.

x="    This    is      a      test   "
echo "${x// /}"
### replace all spaces with * ####
echo "${x// /*}"

Sample outputs:


Updated for accuracy!

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.

Leave a Reply

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

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts