Mauritz
Mauritz

Reputation: 117

Delete parts of filename

I would like to change ugly file names (as a byproduct of my bad programming) like "Booklet xxx.pdf kopie.pdf" to "xxx.pdf". Automator changes it to> " xxx.pdf" (with the very annoying space in front of the file name...

This is what I can come up with…

    tell application "Finder"
    set allFiles to selection
    search of (name of every item of allFiles) for "Booklet "
try
    if file exists then delete "Booklet " of name
end try
    search of (name of every item of allFiles) for ".pdf kopie"
try
    if file exists then delete ".pdf kopie" of name
end try
    end tell

Thanks a lot!

Upvotes: 1

Views: 680

Answers (1)

Lri
Lri

Reputation: 27613

You can rename a file by setting the name property:

activate application "SystemUIServer" -- http://www.openradar.me/9406282
tell application "Finder"
    activate
    repeat with f in (get selection)
        if name of f ends with "kopie.pdf" then
            set name of f to text 9 thru -11 of (get name of f)
        end if
    end repeat
end tell

Or run something like this in a shell:

cd directory; for f in *kopie.pdf; do f2=${f% *}; mv "$f" "${f2##* }"; done

${f% *} removes the shortest ​ * pattern from the end of f and ${f2##* } removes the longest * ​ pattern from the start of f2.

Upvotes: 2

Related Questions