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:
${varName//Pattern/Replacement}
Replace all matches of Pattern with Replacement.
x=" This is a test " echo "${x// /}" ### replace all spaces with * #### echo "${x// /*}"
Sample outputs:
Thisisatest ****This****is******a******test***
Updated for accuracy!
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- My 10 UNIX Command Line Mistakes
- Linux: 20 Iptables Examples For New SysAdmins

- 25 PHP Security Best Practices For Sys Admins
- The Novice Guide To Buying A Linux Laptop
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
Facebook it - Tweet it - Print it -


{ 6 comments… read them below or add one }
Hi,
There is also a builtin bash shell function that you could use, which should be simplier, and quicker (it does not use an extra process like calling sed):
mystring=" Imagination is more important than knowledge "
echo "${mystring// /+}" # this will replace every space by a "+"
+++Imagination+++is+++more+++important+++than+++knowledge+++
echo "${mystring// /}" # this will remove every space
Imaginationismoreimportantthanknowledge
Enjoy !
Many thanks as always :)
My pleasure!
Which is reading again and again your useful and friendly WebSite, as always!
– PP
So, may I know if this topic could be updated to post to introduce the other solutions I gave?
TIA,
– Philippe
Thanks, this info has been updated.
Hi there,
Thanks for the info, you’ve helped me in a little bash script.
Regards,
Roni.