3

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!

Community
  • 1
  • 1
ppapakon
  • 33
  • 1
  • 1
  • 5

3 Answers3

5

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks! But... could you explain the '2d;1r' part? In particular: what if I wanted to replace the 4th line?! – ppapakon Sep 24 '14 at 06:49
  • `2d` is deleting 2nd line and `1r file2` is replacing file2 content after end of line 1. To replace 4th line use: `sed '4d;3r file2' file1` – anubhava Sep 24 '14 at 06:50
  • 1
    Great! Thanks, that was really quick! :-) I went for the inline solution with the small change `sed '2d;1r textfile2' textfile1 > newfile1` to save a new file without destroying the original one. – ppapakon Sep 24 '14 at 06:59
1

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
Community
  • 1
  • 1
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
0

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.

Lazuardi N Putra
  • 428
  • 1
  • 5
  • 15
  • Thank you! I forgot to specify that I cannot type the second line of the original file either. What do I write then instead of "your line" in the above? I tried sed "2s/*/$fromfile2 textfile1 > textfile1new but it didn't work ("unterminated substitute in regular expression"). – ppapakon Sep 24 '14 at 06:50