Review your favorite Linux distribution.
Go Back > Forums > Linux Forums > Linux - Newbie
User Name
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!


  Search this Thread
Old 10-07-2009, 01:07 PM   #1
LQ Newbie
Registered: Oct 2009
Posts: 2

Rep: Reputation: 0
selectively remove blank spaces from string


I'm a newbie to shell scripting and I have the following problem:

I need all spaces between two letters or a letter and a number exchanged for an underscore, but all spaces between a letter and other characters need to remain.

One example for clarity:


force -- lamin 90 [label]
active A -- generation [label]

needed Output:

force -- lamin_90 [label]
active_A -- generation [label]

I tried solving this with sed but obviously s/ /_/g does not work, nor does any s/[a-zA-z0-9] [a-zA-z0-9]/[a-zA-z0-9]_[a-zA-z0-9]/g , because you just can't do this...

Can anyone help me?
Thanks in advance!
Old 10-07-2009, 02:46 PM   #2
Registered: Apr 2009
Distribution: slackware 14.1 64-bit, slackware 14.2 64-bit, SystemRescueCD
Posts: 528

Rep: Reputation: 129Reputation: 129
sed 's/\([a-zA-Z0-9]\) \{1,\}\([a-zA-Z0-9]\)/\1_\2/g'
should do the job
any sequence of
letter/digit followed by 1 space or more and followed
by a letter/digit
is replaced by
the 1st letter/digit followed by '_' and the 2nd letter/digit
Old 10-08-2009, 02:41 AM   #3
LQ Newbie
Registered: Oct 2009
Posts: 2

Original Poster
Rep: Reputation: 0
Thanks a lot for the reply!


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Selectively moving files from a tree with a specific string anywhere in the path waterdragon900 Linux - Newbie 8 08-18-2008 09:57 AM
How to remove spaces from a string pawan_songara Programming 14 08-30-2006 09:20 PM
Removing spaces from string qcoder Programming 3 07-05-2004 12:35 PM
Problem with SED and blank spaces BigLarry Programming 2 06-10-2004 04:57 AM
spaces in a string Longinus Programming 18 03-08-2004 06:02 PM > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 02:58 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration