3

Why is sed writing to my file in reverse order?


I need to read a text file (old_file.txt) that contains the following data:

what's in the file old_file.txt:

1.00
2.00
3.00

I have a second file, which contains:

what's in the file new_file.txt:

AAAA
BBBB
CCCC
DDDD
EEEE
FFFF
GGGG

Now, I need to move the cursor to the nth line of the file new_file.txt, and insert everything that was in old_file.txt, like this:

What I need:

AAAA
BBBB
CCCC
1.00  <-- 
2.00  <-- 
3.00  <--
DDDD
EEEE
FFFF
GGGG

But I get:

What I get:

AAAA
BBBB
CCCC
3.00  <--
2.00  <--
1.00  <--
DDDD
EEEE
FFFF
GGGG

This is my code:

#!/bin/bash

line=3 # line that I need (exemple)

while read x 

    do
        sed -i "${line}a\ $x" new_file.txt

    done < old_file.txt

I don't know why writing happens in reverse order!

1
15

It's happening because your loop appends 1.00 after CCCC, then appends 2.00 after CCCC, then appends 3.00 after CCCC.

To get the order you want, you could instead insert $x before the (n+1)th line - however you don't need a shell loop here at all if you use read from the file directly:

sed -i "${line}"'r old_file.txt' new_file.txt
0
2

Alternative, without sed.

#!/bin/bash

line=3
{ head -${line} new_file.txt ; cat old_file.txt; tail +$((line+1)) new_file.txt ; } 

In other words copy the first $line lines of new_file to the output, then the whole of old_file, then the rest of new_file, from line+1.

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.