LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   sed - substituting multiple occurrances of whitespace with a ':' (https://www.linuxquestions.org/questions/linux-newbie-8/sed-substituting-multiple-occurrances-of-whitespace-with-a-773512/)

simplified 12-04-2009 01:38 PM

sed - substituting multiple occurrances of whitespace with a ':'
 
Hi All

I'm having a few problems removing multiple occurrance of whitespace with a ':'.

Here's the string:
Code:

    8          contact_name                    jsmith
As you can see, there's a lot of whitespace. What I'd like to do is remove the whitespace and substitute a ':' in it's place, so it looks like this:

Code:

8:contact_name:cralph
So, in short I'd like to:
  • Remove the whitespace at the front
    Substitute the remainding whitespace with a ':'

I've tried:

Code:

cat userlist | sed -e 's/[ ]/:/'
...and:

Code:

cat userlist | sed -e 's/[ ]/:/g'
...but can't quite get it right. Any ideas? This is driving me crazy!

TIA, Simplified

druuna 12-04-2009 01:43 PM

Hi,

Is this what you're looking for:

sed -e 's/[[:space:]][[:space:]]*/:/g' -e 's/^://' infile

Replaces all sorts of whitespaces (and removes the leading one).

Hope this helps.

simplified 12-04-2009 03:06 PM

Druuna - you are the man!! Thanks a million :D

pixellany 12-04-2009 04:15 PM

Consider also:
[[:blank:]]
(removes tabs also)

druuna 12-04-2009 04:26 PM

Hi,

For clarity:

[[:blank:]] -> spaces and tabs only (!)
[[:space:]] -> all (!) whitespace chars.

vonbiber 12-04-2009 04:38 PM

Quote:

Originally Posted by simplified (Post 3780052)
Here's the string:
Code:

    8          contact_name                    jsmith
As you can see, there's a lot of whitespace. What I'd like to do is remove the whitespace and substitute a ':' in it's place, so it looks like this:

Code:

8:contact_name:cralph

ok, you want to replace any occurence of one or more space(s) by a ':'
If it's just spaces (no tabs) this should work
Code:

cat userlist | sed 's/ \{1,\}/:/g'
If there are tabs as well as spaces:
Code:

cat userlist | sed 's/[ \t]\{1,\}/:/g'

druuna 12-04-2009 04:42 PM

@vonbiber: You are forgetting the removal of the leading whitespace..... Thread was already solved as well.

pixellany 12-04-2009 06:45 PM

Quote:

Originally Posted by druuna (Post 3780236)
Hi,

For clarity:

[[:blank:]] -> spaces and tabs only (!)
[[:space:]] -> all (!) whitespace chars.

Ooooops!! 3rd mistake this year.....;)

Why do I think that is counter-intuitive?

Other than a newline, what is whitespace that is not a space or a tab?

druuna 12-05-2009 03:38 AM

@pixellany: Besides the space and (horizontal) tab it also removes vertical tabs and formfeeds.

[ \t\r\n\v\f] == [[:space::]]
[ \t] == [[::blank::]]

I can understand the confusion :)


All times are GMT -5. The time now is 04:37 AM.