Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
You seem to be making a new account for each question. – user39428 May 27 '13 at 6:16

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
share|improve this answer

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
share|improve this answer
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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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