LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Script to create simple html from text file (https://www.linuxquestions.org/questions/programming-9/script-to-create-simple-html-from-text-file-759052/)

the_mulletator 10-01-2009 03:11 PM

Script to create simple html from text file
 
I am working on a script to convert a comma seperated text file into html code line by line.
I am a newbie with scripts (and programming in general)

The text file is like so:
Code:

link url, image url, description
and I want it to output this:
Code:

<td><a href=”link url”><img src="image url" alt=”description" /></a></td>
Here is what I have so far:
Code:

#!/bin/bash
var1='<td><a href=”'
var2='”><img src="'
var3='" alt=”thumbnail image" /></a></td>'
while read line
do
echo $var1$line$var2$line$var3
done < gallery.txt

It puts the entire line into the html so its no good. I'll probably need to use awk (I think).

cpuobsessed 10-01-2009 03:13 PM

Look into Ruby or Python, they both have a lot of libraries available specially for such tasks.

smeezekitty 10-01-2009 03:14 PM

tip the html generator needs to be inside the loop
thats aout all i kow about she scripts
sorry my keyboard has stuck keys

gzunk 10-01-2009 03:36 PM

This'll do it in perl

Code:

use strict;
use warnings;

# Open the input file
open (my $fh, "<", "input.txt") or die $!;

# Loop around the file performing the replacements
while (<$fh>) {
        chomp;
        my ($url, $image, $description) = split /,/;
        print "<td><a href=\"$url\"><img src=\"$image\" alt=\"$description\"/></a></td>\n";
}

close $fh;

input.txt looks like this:

Code:

link1 url,image1 url,description1
link2 url,image2 url,description2


catkin 10-01-2009 03:38 PM

Assuming it's OK to modify gallery.txt, taking out the spaces after the commas (if not that can be fixed), this should do it
Code:

#!/bin/bash

while read line
do
    IFS=','
    array=($line)
    unset IFS
    echo '<td><a href=”'"${array[0]}"'”><img src="'"${array[1]}"'" alt=”'"${array[2]}"'" /></a></td>'
done < gallery.txt

EDIT: on second thoughts this is a bit tidier
Code:

#!/bin/bash

while IFS=',' read link_url image_url desc
do
    echo '<td><a href=”'"$link_url"'”><img src="'"$image_url"'" alt=”'"$desc"'" /></a></td>'
done < gallery.txt


the_mulletator 10-01-2009 04:23 PM

Thanks guys.
I used the perl one. It works great!


All times are GMT -5. The time now is 08:14 AM.