Search code examples
regexmakefilefilenames

Delete space and replace non-ASCII characters in filenames via a loop with a makefile


In a folder full of image files I would like to delete any spaces in the file name. Furthermore I want that non-ASCII characters are replaced by a dash -. This needs to be done via a makefile.

Note: The final dot before the suffix/extension of the file has to remain.

example:

"Fig. 3_16mm_300dpi_1to1_obv.tif" --> "Fig-3-16mm-300dpi-1to1-obv.tif"

My approach so far

IMGPATH  = "workfiles/inserts/figures"

cleanfigures:
    cd $(IMGPATH) && \
        for f in *; \
        do \
        mv -v "$$f" "$${f//[^a-zA-Z0-9](?=.*?\.)/-}" ; \
        done

The regex command ([^a-zA-Z0-9](?=.*?\.)) is fine when I test it with https://regex101.com/ but it will not work accordingly with the makefile, since nothing is renamed or replaced.


Solution

  • You said you wanted to change all non-ASCII characters to -. However based on your attempt, it seems you only want to transform to - those characters which are not digits or "plain" letters (by plain I mean non accented, non fancy, ...).

    cleanfigures:
        for f in *; \
        do \
        ext="$${f##*.}" ; \
        base="$${f%.*}" ; \
        newbase="$${base//[^a-zA-Z0-9 ]/-}" ; \
        echo "$$f" "$${newbase// /}.$$ext" ; \
        done