ppapakon
ppapakon

Reputation: 43

Replace line in text file with line from other text file

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!

Upvotes: 4

Views: 25389

Answers (3)

jaypal singh
jaypal singh

Reputation: 77185

I would go with the sed solution anubhava posted. Here is an alternate in bash.

#!/bin/bash

while read -r line; do 
    (( ++linenum == 2 )) && while read -r line; do 
        echo "$line"
        continue 2    # optional param to come out of nested loop
    done < textfile2
    echo "$line"; 
done < textfile1

or using awk:

awk 'FNR==2{if((getline line < "textfile2") > 0) print line; next}1' textfile1

Upvotes: 1

Lazuardi N Putra
Lazuardi N Putra

Reputation: 428

Is this script or directly from terminal? If this is a script. You can try to store file 2 into variable fromfile2=$(cat textfile2) Then replace your textfile1 with sed -i "s/your line/$fromfile2". Hope it helps.

Upvotes: 0

anubhava
anubhava

Reputation: 786359

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

Upvotes: 5

Related Questions