Combining sed actions

Let's say I have an input file looking like:

ID1
1    5
6    8
ID2
1    4
5    7
 

I'm trying to formulate a loop that can combine these actions:

  • If the line begins with a letter: replace the '\ n' after a field containing characters with a '\ t' (sed 's / \ n / \ t / g' )
  • If the line begins with a number: replace every '\ t' and '\ n' with a comma (sed 's / \ t /, / g; s / \ n /, / g ') EXCEPT if the next line begins with a letter (sed 's / \ t /, / g')

Expected output:

ID1     1, 5, 6, 8
ID2     1, 4, 5, 7

This is what I tried so far (but I have no idea of how I could format it properly) :

sed '$1 ~ /^[A-Z]|^[1-9]/ {if ~ /^[A-Z] 's/\n/\t/g'; else if ~ /^[1-9] 's/\n/,/g'}'

Any help would be appreciated :smiley: Thanks in advance

sed does not have if...else constructs. You could use awk for this. With sed and exactly the sample structure that you supplied, this might work:

sed '/^[[:alpha:]]/ {N;N;s/\n/\t/g;s/\t/, /g;s/,/\t/}' file
ID1     1, 5, 6, 8
ID2     1, 4, 5, 7

Hi,
Another sed solution (general):

$ cat iid.txt
ID1
1       5
6       8
ID2
1       4
5       7
5       7
5       7

ID3
1       4
$ sed  -e ':yy;/^[A-Z]/{s/$/\t/;:xx;$bzz;N;s/\(\n\|\t\)\([0-9]\)/,\2/g;txx;};h;s/.*\n//;x;s/,//;s/\n.*//p;x;tyy;:zz;s/,//' iid.txt
ID1     1,5,6,8
ID2     1,4,5,7,5,7,5,7

ID3     1,4