1

I want to replace the contents between two lines specified by line numbers using bash. For example. I have a file sample.txt, it has the following contents.

apple
peach
orange
juice
toy
computer
phone

I have a variable called var

var="cup\nbook"

I want to replace the contents between the second line and the 5th line(including the two lines) in sample.txt with the contents stored in var, so the final contents after the modification in file sample.txt should be

apple
cup
book
computer
phone

How to do that?

anubhava
  • 761,203
  • 64
  • 569
  • 643
Searene
  • 25,920
  • 39
  • 129
  • 186

2 Answers2

2

You may use awk:

var="cup\nbook"

awk -v var="$var" 'NR==2{print var} NR<2 || NR>5' file

apple
cup
book
computer
phone

Here is a sed solution that works with OSX sed (note definition of variable var):

var=$'cup\\\nbook'
sed "2,5c\\
$var
" file

apple
cup
book
computer
phone
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

With sed:

var="cup\nbook"
sed "2,5c$var" file
Léa Gris
  • 17,497
  • 4
  • 32
  • 41