Paul Paul - 3 months ago 7
Perl Question

adding a comma in the text file

I have a text file in the following format

group1: 2010EL-1749 2010EL-1749_00001 3554-08 3554-08_01855 2010EL-1749_00002
group2: 2010EL-1749 2010EL-1749_00002 3554-08 3554-08_01856 2010EL-1749_00001
group7: 3554-08 2010EL-1749_00001 3554-08_01855


And would like to add a comma in between the ids as shown below

group1: 2010EL-1749,2010EL-1749_00001,3554-08,3554-08_01855,2010EL-1749_00002
group2: 2010EL-1749,2010EL-1749_00002,3554-08,3554-08_01856,2010EL-1749_00001
group7: 3554-08,2010EL-1749_00001,3554-08_01855

Answer
$ sed 's/ /,/g; s/,/ /' textfile
group1: 2010EL-1749,2010EL-1749_00001,3554-08,3554-08_01855,2010EL-1749_00002
group2: 2010EL-1749,2010EL-1749_00002,3554-08,3554-08_01856,2010EL-1749_00001
group7: 3554-08,2010EL-1749_00001,3554-08_01855

This works by changing all spaces to commas: s/ /,/g. It then changes the first comma back to a space: s/,/ /.

s/,/ / is an example of a substitute command. The form is s/old/new/ where old is a regular expression and the first match for old is replaced with new. If we add a g to the end of the command, like s/ /,/g, then not just the first is replaced: all non-overlapping matches are replaced.

This approach assumes that no ID contains a space and no group name contains a comma.

To change the file in place:

sed -i.bak 's/ /,/g; s/,/ /' textfile