0

Im trying to append a Block of html code (that is in a Shell Variable) after a specific line. for example :-

name="john"
link="www.test.com"
jobname="testjob"

data="<tr>
<td>$name</td>
<td><a href=$link>$link</a></td>
<td>$jobname</td>
<td>Running: <progress value="22" max="100">
</progress>
</td>
<td>Running: <progress value="22" max="100">
</progress>
</td>
<tr>"

sed '/\<tbody\>/a \\$data' filename

filename Contains :-

<html>
<tbody>

I need to append the Shall Variable contents after line in filename. Appreciate the responses.

John
  • 89
  • 1
  • 10
  • Not clear, please do mention your problem more clearly and let us know then? – RavinderSingh13 Jul 11 '18 at 10:15
  • 1
    I would argue that sed isn't the right tool for this job, for instance you will run into issues with escaping of `$data`. However, try switching the `/` delimiter to something else and use `"` instead: `sed "s^^$data^g" filename`. – ext Jul 11 '18 at 10:32

2 Answers2

1

If you can store $data in a file instead of shell variable (a temporary file is ok) you can use r filename to read and insert the content:

echo $data > temp.html
sed "/<tbody>/ r temp.html" filename

See sed command list and less frequently used commands for more details.

ext
  • 2,593
  • 4
  • 32
  • 45
0

sed is for s/old/new/, that is all (e.g. see Is it possible to escape regex metacharacters reliably with sed for the horrors involved in trying to get sed to treat a string as a string), and you need to fix your quoting and escaping. Try this (untested):

name='john'
link='www.test.com'
jobname='testjob'

data='<tr>
<td>'"$name"'</td>
<td><a href='"$link"'>'"$link"'</a></td>
<td>'"$jobname"'</td>
<td>Running: <progress value="22" max="100">
</progress>
</td>
<td>Running: <progress value="22" max="100">
</progress>
</td>
<tr>'

awk '
BEGIN {
    data = ARGV[2]
    ARGV[2] = ""
    ARGC--
}
{ print }
/<tbody>/ { print data }
' file "$data"
Ed Morton
  • 188,023
  • 17
  • 78
  • 185