Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line in text file with line from other text file

Tags:

bash

replace

My question is a variant of the following one:

bash: replace an entire line in a text file

The problem there was to replace the Nth line of a file with a given string (a replacement line). In my case, I can't just type the replacement line, but I have to read it from another file.

For example:

textfile1:

my line
your line
his line
her line

textfile2:

our line

I want to replace the 2nd line of textfile1 with the line from textfile2.

I thought I could just read the textfile2

while IFS= read SingleLine 

etc. and then use $SingleLine as the replacement line, but I failed... Depending on the type of quotes I used (please excuse my ignorance...) I ended up replacing the line in question with the text $SingleLine or with SingleLine or just getting an error message :-[

I am sure you can help me!!

EDIT about the solution: I went for the inline solution with the small change

sed '2d;1r textfile2' textfile1 > newfile1 

To replace the Nth line, the solution would be (see comments on accepted solution for explanations)

sed 'Nd;Mr textfile2' textfile1 > newfile1 

with N the desired line number and M=N-1.

Thank you all!

like image 340
ppapakon Avatar asked Oct 31 '25 03:10

ppapakon


1 Answers

Using sed:

sed '2d;1r file2' file1
my line
our line
his line
her line

To make it inline edit:

sed -i.bak '2d;1r file2' file1
like image 196
anubhava Avatar answered Nov 01 '25 19:11

anubhava