newzad
newzad

Reputation: 706

Insert content of a file to another file on Linux

I have two files. I want to insert the content of the first file(file1) to the second file (file2) between some codes (second file is a script). For example the second file should look like this

upcode...
#upcode ends here
file1 content
downcode ...

upcode #upcode ends here and downcode should never change.

How this can be done?

Upvotes: 0

Views: 373

Answers (3)

kev
kev

Reputation: 161614

You can try sed:

sed -e '/file1 content/{r file1' -e 'd}' file2
  • /pattern/: pattern to match line
  • r file1: read file1
  • d: delete line

Note: you can add -i option to change file2 inplace.

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 246744

while IFS= read -r f2line; do
    echo "$f2line"
    [[ "$f2line" = "#upcode ends here" ]] && cat file1
done < file2 > merged_file

or to edit file2 in place

ed file2 <<END
/#upcode ends here/ r file1
w
q
END

Upvotes: 1

Bill
Bill

Reputation: 5764

Here is a script to do that (note that your start tag has to be unique in the file)--

#!/bin/bash

start="what you need"

touch file2.tmp

while read line
do
  if [ "$line" = "$start" ]
  then
     echo "$line" >> file2.tmp
     cat file2 >> file2.tmp
  fi
  echo "$line" >> file2.tmp
done < file1
#mv file2.tmp file1 -- moves (i.e. renames) file2.tmp as file1. 

Upvotes: 2

Related Questions