3

I have a file like the following:

a,b,c,d,e,f
1,2,3,4,5,6
7,8,9,0,1,2

I need to join the last two lines with a comma, like so:

a,b,c,d,e,f
1,2,3,4,5,6,7,8,9,0,1,2

The problem is that this is all inside a loop that will add two new lines to that file, say

a,b,c,d,e,f
1,2,3,4,5,6,7,8,9,0,1,2
0,9,8,7,6,5
4,3,2,1,0,9

And now I need to do the same to that last line for the file to end like

a,b,c,d,e,f
1,2,3,4,5,6,7,8,9,0,1,2
0,9,8,7,6,5,4,3,2,1,0,9

So, in only a few words, I need to replace the last new line of a text file with a comma, but only the last line, as lines are being added.

I've tried several things but they don't work. The last one was sed '$!N;s/\n/,/' dna.data, but it applies to all lines with a newline.

Any ideas?

4

If the file does not end with a newline, you just need to address the last substitute command (use the -i flag of sed to change the file inplace):

$ sed '$!N;$s/\n/,/' dna.data
a,b,c,d,e,f
1,2,3,4,5,6,7,8,9,0,1,2
0,9,8,7,6,5,4,3,2,1,0,9  

If the file ends with a newline, you can use the editor ex:

$ ex dna.data
$-1s/\n/,/
1,2,3,4,5,6,7,8,9,0,1,2
x

or in one line

echo -e '$-1s/\\n/,/\nx' | ex dna.data
2

This might work or for you (GNU sed):

sed -i '$!N;$s/\n/,/;P;D' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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