Insert output into file at line number

I need to insert the output of a script into a specific line number of a txt file.
I've read the Sed man page and searched the forums and it's not immediately clear how I would go about doing this.

Hi ,
Please try below code

outfilename=`ls -1 *.out`
if [ $? -eq 0 ]
then
for i in `cat $outfilename`
do
txtfilename=`grep -l $i *.txt`
linenumber=`grep -n $i $txtfilename|cut -f1 -d ":" `
sed -i "$linenumber"'H' $txtfilename
done

fi

Simple way is write a two line shell script.

Something like this,

$ cat  t
a
b
c
d

$ cat t.sh
#! /usr/bin/sh

a=`echo "test"` # Execute the command and store the output in a variable

sed  -i "4 i\\$a" t  ## 4 i - is to insert the data in 3rd line ( give appropriately) 

$ cat t
a
b
c
test
d


---------- Post updated at 01:39 AM ---------- Previous update was at 01:27 AM ----------

Sorry, it inserts "test" as a 4th line.

Hi,

VAR="Hello there"

Try this

sed "3s/^/$VAR\n/" infile

-or-

sed "3i$VAR" infile

You need to test if the value of VAR is empty beforehand, otherwise the first command will still insert an empy line, and the second command will fail. If your sed supports inline replacement, you can use sed -i, otherwise you have to do "> newfile" and mv the result to the original file

An example how to insert file.txt on line 3 of your file:

awk 'NR==3{system("cat file.txt")}1' file > newfile