Help with copying lines from different files.

I am new to Linux and have a challenging task.
I have 3 data files, and need to do the following:

  1. Go to line 31 of file 1, delete it
  2. Read 1 line from file 2 and add in place of deleted line
  3. Go to line 97 of file I delete it and then read the line 1 from file 2 and add in place of that deleted file.

The thing is also important to keep the same file i.e file , it is not to be changed.
I tried different versions of sed and perl, with buffer copying tricks but was not successful. :wall:

I am open for all suggestions and request the experts to give me suggestions.

Well, it's very clunky, but you could try:-

echo "31Gddk:r !head -1 file2\n:wq"|vi file1
echo "97Gddk:r !head -1 file2\n:wq"|vi file1

Does that do it? I feel a proper sed or awk would be better if the files are large. Additionally, remember the vi has limitation such as maximum line length and space for the temporary files it uses, often in /var

You could also:-

(head -30 file1;head -1 file2;head -96 file1|tail +32;head -1 file2;tail +98 file1) > outputfile

You would need to check the exact records this catches as head & tail vary accourding to OS version. You also cannot write this back to file1 until you have created the replacement file, so you might hit space issues.

Could you expand on the reasons for the edit and sizes of files etc.

I hope that this helps if it's a small enough file to be processed each time.

Robin
Liverpool/Blackburn
UK

1 Like

This leaves all of the old files unchanged, creates 2 new ones with the change

newline=$(head -1 file2)
awk -v n="$newline" 'NR==31 {print v; next} {print} ' file1 > newfile1
awk -v n="$newline" 'NR==97 {print v; next} {print} ' fileII > newfileII

newfile1 and newfileII are the names of the new files.