I have a problem that (I think) require a bit of script-magic - not sure what would be best though...

I have one directory with lots pictures in different formats - jpg, gif, png, tiff and svg.

Some (not all!) of the png-and svg-files are in pairs - ie. one png and one svg version of the same image, both with the same filename, except that the suffix differs (eg. figleaf.png and figleaf.svg).

I need a script that will take the file-list (made by ls), and remove the svg-version of all twins, leaving just the png-version. All other files (non twins) - including svg-files without a png-twin - should remain in the list (together with the png-version of the twins). Alternatively, a script that creates a list of all svg-files with a corresponding png-twin.

I think some of twins may have slight difference in between the versions - eg. figleaf.png and FigLeaf.svg - so it would be great if the script could be optionally changed to ignore the case of the letters.


You could do it using bash/ksh :

for i in *.svg; do test -e "${i%.*}.png" && rm "$i"; done

Or, formatted differently :

for i in *.svg; do
    test -e "${i%.*}.png" && rm "$i"

Replace the rm with echo to test before doing the actual deleting.


sputnick just edited a solution very similar to this in his answer, you should take his as he was the first to answer.

  • @sputnick Yes, I saw your edit after I posted my answer. Just edited my answer accordingly. – user43791 Dec 23 '14 at 16:54

Try doing this using :

(remove the i modifier in the substitution if you want to be case sensitive)

$ perl -e '
    foreach my $file (<*.png>) {
       ($ext_free = $file) =~ s/\.png//i;
       unlink "$ext_free.svg" if -e "$ext_free.svg";
' *.[Pp][Nn][Gg]

To try it before, put a print instead of unlink.

or using :

shopt -s nocaseglob # case insensitive
# use 'shopt -u nocaseglob' for case sensitive
for file in *.png; do
    [[ -e ${file%.png}.svg ]] && rm -f "${file%.png}.svg"

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.