Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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
share|improve this answer
add comment

This might work or for you (GNU sed):

sed -i '$!N;$s/\n/,/;P;D' file
share|improve this answer
add comment

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.