0

I wanted to create a script that I could check .xhtml files for images and add alt tags if needed. While searching I found regular expressions and did man on glob but I'm unsure on where or what to search within awk and sed. What would be the best option to do the following:

<img class="something" width="something" height="something" src="folder/folder/image.png" />

<img id="something" src="folder/folder/file.png" />

I wanted the desired script to detect if an alt="" is present if not alt the file name.

End desired format:

<img class="something" width="something" height="something" src="folder/folder/image.png" alt="image"/>

<img id="something" src="folder/folder/file.png" alt="file"/>

I know it can be done but Im not sure where to read about it.

  • Find <img with the ending />
  • Within img tag detect alt=""
  • if alt="" is not present record name before file type and insert into ""
  • 3
    Just a warning: it is not possible to parse XML-type languages reliably with regular expressions as XML is not a regular language. The best you can do is an ad-hoc approximation for a restricted subset of valid (X)HTML. It'd help if you could list as many characteristics of your input as possible. E.g. does the string <img occur outside the context of a valid image tag anywhere? How about alt=? Can tags span multiple lines? Complications like this are what make the problem impossible unless you place some additional restrictions on it. – jw013 Dec 14 '12 at 21:54
  • I wouldn't know where to begin. I just need to find a way to identify all img tags and make sure an alt tag is present – DᴀʀᴛʜVᴀᴅᴇʀ Dec 14 '12 at 22:11
3

One way using perl with the help of the XML::Twig parser:

#!/usr/bin/env perl

use strict;
use warnings;
use XML::Twig;
use File::Spec;

my $twig = XML::Twig->new(
    twig_handlers => {

        ## For each 'img' tag execute following function...
        'img' => sub {

            ## If it doesn't have an 'alt' attribute...
            if ( ! $_->att_exists( 'alt' ) ) { 

                ## Get value of 'src' tag.
                my $src = $_->att( 'src' );
                return unless $src;

                ## Get last part of the path and remove extension.
                my $src_file = (File::Spec->splitpath( $src ))[2] || q{};
                $src_file =~ s/\.[^.]+$//;

                ## Create the 'alt' attribute.
                $_->set_att( 'alt', $src_file );
            }   
        }   
    },  
    pretty_print => 'indented',
)->parsefile( shift )->print;

Run it with your xml file as unique argument, like:

perl script.pl xmlfile

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.