I have a script that takes the results of a command and puts them into a html code.

Here's what I have so far...


list_dir=`ls -t downloads/`

for i in $list_dir
#       echo "<a href=\"downloads/$i\">$i</a>"
#----attempt 1   
  ` sed -n 'H;${x;s/placeholder .*\n/<a href="downloads/$i">$i</a>\
                       &/;p;}' index.html`

I'm trying to get the results of the for loop to replace the contents of the html file where it says "placeholder" (I would rather have it just insert the content below a certain point without having the placeholders). I'm not too certain how to go about this.


Parameter substitutions can be used to replace text without any escaping issues:

output=$(ls -t downloads | while IFS= read -r f; do
    echo "<a href=\"downloads/$f\">$f</a>"

echo "$html" > output.html

You could also use awk -v to pass the replacement text as a variable:

awk -v v="$output" '{sub("placeholder",v);print}' index.html > output.html

Or use Ruby to replace a multi-line pattern without requiring a placeholder:

echo "$output" | ruby -i -e 'print gets(nil).sub(/<a .*<\/a>\n/m, STDIN.read)' index.html

If you just want to replace the entire contents of the file, rather than somehow inserting your output in the middle, then your attempt #1 may be closer to what you want than an approach based on sed, if you redirect the output of the entire loop:


list_dir=`ls -t downloads/`

for i in $list_dir
    echo "<a href=\"downloads/$i\">$i</a>"
done > index.html
  • Thanks for your reply. I would do that, but there's html code that needs to be preserved so I have to insert the results in a specific place. – tyler May 27 '13 at 5:21

There are multiple problems with your sed line, e.g. with variable $i in single quotes never getting expanded.

Given the following index.html:

<!-- placeholder -->

try using a intermediary files for the sed in/output:


list_dir=`ls -t downloads/`

cp index.html out.html

for i in $list_dir
   sed "s/<!-- placeholder -->/<a href='downloads\/$i'>$i<\/a>\n<!-- placeholde
r -->/" out.html > tmp.html
   mv tmp.html out.html
cat out.html

Of course you will run into problems when there are filenames with spaces in them, but that is another issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.