Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a text file where each line has the format like this...

25126 Akers, David

And I'm needing to put it in a format like this to insert into a database...

25126;Akers, David;

Only problem is there might be some with names having spaces like...

25257 Ah You, C.J.

I was told I should use grep but I'm not sure how to go about doing it.

share|improve this question
    
Trying to make it clear: Does number always follow by space or can there be space in number as well? for e.g. 24 557 name, name Next does two names (fields) always separated by a comma? well if u answer no and yes to above questions then split number on the basis of space and name fields on the basis of comma –  wisemonkey Aug 22 '11 at 19:53
    
Number is always followed by one space, and the name is always separated by a comma. I'm not familiar enough with grep to know how to do it though. That's why I was hoping someone could help. –  fwaokda Aug 22 '11 at 19:57
    
You probably want to use sed not grep. Also, you might ask in the unix and linux stackexchange or even stackoverflow since this is more of a shell question no specific to Ubuntu. –  Kris Harper Aug 22 '11 at 20:04
    
oh! ok my apologies will do. –  fwaokda Aug 22 '11 at 20:10

1 Answer 1

up vote 3 down vote accepted

grep is not suitable for such a task, because it is a search tool, but if I understand correctly the problem, you can use sed, as in the following example:

sed 's/^\([0-9]\+\) \(.*\)$/\1;\2;/' input-file >output-file

To preventively check that all lines conform to the above pattern, run the following command

sed -n '/^\([0-9]\+\) \(.*\)$/!p' input-file

that should return nothing.

share|improve this answer
    
Thanks works beautifully! –  fwaokda Aug 22 '11 at 20:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.