0

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?

newzad
  • 706
  • 1
  • 14
  • 29
  • what is `upcode` and `downcode`. Depending on what they are, the solution may change. – Bill May 15 '13 at 01:37
  • 1
    BTW, if all you want to insert `file1` at the beginning (because `downcode` really dnt have any significance)...do something like this -- `echo "#!/bin/bash" > file2.tmp; cat file1>> file2.tmp; cat file2 >> file2.tmp; mv file2.tmp file2` – Bill May 15 '13 at 01:39
  • Perfect! Thanks. However, I would like to see a general solution when instead of #!/bin/bash" there are lines of codes. – newzad May 15 '13 at 01:42
  • You should delete `#!/bin/sh` from your question, since that is what is `upcode` for you...right? – Bill May 15 '13 at 01:55
  • I put it to there to point the place where upcode ends. It is better to change it to "upcode ends here" – newzad May 15 '13 at 02:02

3 Answers3

3

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.

kev
  • 155,172
  • 47
  • 273
  • 272
  • That seems to be a very good solution but I didn't understand it. We search for a string, like "#upcode ends here" in file2 and then intert file1 content after it, as I understood from your solution more and less. Why we need to read file1? – newzad May 15 '13 at 02:32
2

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. 
Bill
  • 5,263
  • 6
  • 35
  • 50
1
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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352