Tips & Tricks, Questions regarding shell scripts, awk, perl, sed and much more.

Advertisement


DNS query tools & Network tools (Ping & Traceroute)

SED how to remove multiple white spaces from a string

Postby debuser » Thu Feb 25, 2010 2:14 pm

This article will show only a few example that would be enough for most people:

How to remove multiple white spaces from a string:
Code: Select all
# echo 'some     white            spaces' | sed 's/  *//g'
somewhitespaces


How to replace multiple white spaces from a string:
Code: Select all
# echo 'some     white            spaces' | sed 's/  */\ /g'
some white spaces


Above sed command replaces multiple spaces with a single space. You can adjust it to replace multiple spaces with other characters, like pipe (|):
Code: Select all
# echo 'some     white            spaces' | sed 's/  */\|/g'
some|white|spaces


Special attention needs to be paid to the start and end of the lines:
Code: Select all
# echo '             some     white            spaces ' | sed 's/  */\|/g'
|some|white|spaces|


Above example contains multiple spaces at the beginning and one space at the end of the line. Sed replaced all with a pipe.
All of the above sed regular expressions in the replaced field (/ */) contain two spaces, followed by a ster (*). Omitting this will mess up your script.
debuser
 
Posts: 70
Joined: Thu Aug 06, 2009 9:48 am


Advertisement


Return to Shell Scripting and Programming

Similar topics


Who is online

Users browsing this forum: No registered users and 0 guests

cron