Mina Hafzalla
Mina Hafzalla

Reputation: 2821

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

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.

Upvotes: 5

Views: 5421

Answers (4)

NeronLeVelu
NeronLeVelu

Reputation: 10039

if you can use awk:

awk 'NR!=FNR || NR<4' Result.txt Data.txt

Upvotes: 1

Craig Estey
Craig Estey

Reputation: 33601

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

Upvotes: 4

baldr
baldr

Reputation: 2999

head -n 3 /path/to/file/results.txt > /path/to/file/results.txt
cat /path/to/file/data.txt >> /path/to/file/results.txt

Upvotes: 1

Aaron
Aaron

Reputation: 24812

You can use process substitution to give cat a fifo which it will be able to read from :

cat <(head -3 result.txt) data.txt > result.txt

Upvotes: 2

Related Questions