Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy data from file to another file starting from specific line

Tags:

linux

bash

unix

sed

I have two files data.txt and results.txt, assuming there are 5 lines in data.txt, I want to copy all these lines and paste them in file results.txt starting from the line number 4.

Here is a sample below:

Data.txt file:

stack
ping
dns
ip
remote

Results.txt file:

# here are some text
# please do not edit these lines
# blah blah..
this is the 4th line that data should go on.

I've tried sed with various combinations but I couldn't make it work, I'm not sure if it fit for that purpose as well.

sed -n '4p' /path/to/file/data.txt > /path/to/file/results.txt

The above code copies line 4 only. That isn't what I'm trying to achieve. As I said above, I need to copy all lines from data.txt and paste them in results.txt but it has to start from line 4 without modifying or overriding the first 3 lines.

Any help is greatly appreciated.

EDIT:

I want to override the copied data starting from line number 4 in the file results.txt. So, I want to leave the first 3 lines without modifications and override the rest of the file with the data copied from data.txt file.

like image 808
Mina Hafzalla Avatar asked Dec 23 '15 21:12

Mina Hafzalla


1 Answers

Here's a way that works well from cron. Less chance of losing data or corrupting the file:

# preserve first lines of results
head -3 results.txt > results.TMP

# append new data
cat data.txt >> results.TMP

# rename output file atomically in case of system crash
mv results.TMP results.txt
like image 142
Craig Estey Avatar answered Oct 14 '22 02:10

Craig Estey