-1

I have a file called source.txt which contains the following lines:-

the
quick
brown
fox
jumped
over
the
lazy
dog

I want to search for the 'fox' line and delete it and all lines that follow, up to and including the 'over' line. Then I want to insert the contents of another file (fruit.txt) in place of those lines. Fruit contains:-

apples
bananas
pears

So the result should be a file that looks like this:-

the
quick
brown
apples
bananas
pears
the
lazy
dog

I think this will be possible to do using the sed command.

This command successfully removes the lines:-

sed -i -e '/fox/,/over/d' source.txt 

And this command almost works, but inserts the contents of the fruit.txt file three times, once for each matching line:-

sed -i -e '/fox/,/over/{r fruit.txt' -e 'd}' source.txt

Any help would be greatly appreciated!

  • Just insert when you see `fox` and then delete all lines in the range separately. – tripleee Oct 30 '18 at 09:59
  • 3
    `/fox/,/over/{ … }` will be executed for each line between `/fox/` and `/over/`. You need to make sure the insert only happens once, eg. on the fox line: `sed -i -e '/fox/,/over/{/fox/r fruit.txt' -e 'd}' source.txt`. – Robin479 Oct 30 '18 at 10:04
  • 2
    @Robin479 I concur, however on reflection `fox` could occur again within the range, perhaps better to match on the last line of the range i.e. `over` – potong Oct 30 '18 at 10:09
  • Brilliant, thanks all! – Robert Brawn Oct 30 '18 at 10:24
  • 1
    Possible duplicate of [Insert contents of a file after specific pattern match](https://stackoverflow.com/q/16715373/608639), [Insert specific lines from file before first occurrence of pattern using Sed](https://stackoverflow.com/q/32763022/608639), [Insert content of file after first pattern match using sed](https://stackoverflow.com/q/21729434/608639), etc. – jww Oct 30 '18 at 23:21

1 Answers1

0

In this condition you have to delete the undesired one by this command

sed -i -e '/fox/,/over/d' source.txt

Then add the required one by this command

sed -i -e '/brown/ r fruit.txt' source.txt

I hope it will help you

Atif
  • 11
  • 2