views:

56

answers:

5

Hi!

I am struggling with formatting of a db2 query. I would like to replace 2 or more spaces in a string with a semicolon. I know how to do it with all spaces, the question would be how to change only 2 or more spaces :P

Here is an example, i would like to change this:

john doe    1900-01-01    california

to

john doe;1900-01-01;california

The problem is that i have one space in the name field, so i can't use a simple tr command. In my real job, there can be a single space in any field.

I would appreciate your help very much! Thanks in advance!

A: 

How do you know it should be:

"john doe;1900-01-01;california"

and not:

"john;doe 1900-01-01;california" 

?

karlphillip
If you do a query, there are always more than 2 spaces between two columns. and in the data, between first and last name, or days in a date, never more than one. I hope at least :)
Aron
@karl: This should have been posted as a comment to the question since it doesn't contain an answer.
Dennis Williamson
Thank you, I'm still learning how this works. Won't happen again.
karlphillip
+2  A: 

Try using

sed -i 's/   */\;/g' your-file

This will substitute every 2 or more spaces with a ; in the file you pass it.

Alberto Zaccagni
+4  A: 
$ sed 's/   */;/g' 
john doe   1900-01-01  california 
john doe;1900-01-01;california 
one space  two  spaces   three    spaces
one space;two;spaces;three;spaces
msw
This also works: `sed 's/ \+/;/g'` (two spaces and an escaped plus sign instead of three spaces and an asterisk).
Dennis Williamson
@Dennis: that is true in most modern sed implementations. Unfortunately, there are still versions in the wild which don't support `\+` so I wasted an octet in the interests of portability.
msw
A: 

The best way is to query your database tables with the proper delimiter (ie ";"). See if you can do it that way. Otherwise,

$ echo "john doe 1900-01-01 california" | sed 's/ /;/2g'
john doe;1900-01-01;california

This will break if the name has 3 or more words.

ghostdog74
`2g` works for GNU `sed`. Other versions may work differently when you use a number and `g` together. Also, there were some missing spaces in the OP's question as it was originally posted. An edit fixed this.
Dennis Williamson
A: 

AAHHH!!!!

Many many thanks for the quick answers! Thank You ALL!! and so quick.... maan... i was really trying to solve this since 3 hours...

Aron
So accept one of the answers, and next time, use proper formatting.
Anders
@Aron: This should have been posted as a comment on your original question (or an edit to it) since it's not an answer to the question.
Dennis Williamson