使用AppleScript用短划线替换文件名中的无效字符 [英] Replacing invalid characters in the filename with dashes using AppleScript
问题描述
我的目标是使用AppleScript或Javascript在Automator中创建服务,该服务将所选文件名()[\\/:"*?<>|]+_
的所有无效字符和空格替换为短划线(-
),并使文件名小写.
My goal is to create service in Automator using AppleScript or Javascript which replaces all invalid characters of selected filename ()[\\/:"*?<>|]+_
and spaces with dashes (-
) and make filename lowercase.
推荐答案
可以通过使用Automator Service中的Bash Shell脚本来替换文件/文件夹名称中不允许的字符.
The replacement of impermissible characters in a file/folder name can be achieved by utilizing a Bash Shell script in your Automator Service.
以下步骤描述了如何实现:
The following steps describe how to achieve this:
- 启动自动化器
- 键入⌘N,或从菜单栏中选择
File
>New
. - 选择
Service
并单击Choose
-
在画布区域的顶部,按以下方式配置其设置:
- Launch Automator
- Type ⌘N, or choose
File
>New
from the Menu bar. - Select
Service
and clickChoose
At the top of the canvas area configure its settings as follows:
在左侧面板/列的顶部选择Library
:
Select Library
at the top of the panel/column on the left:
-
在搜索字段中输入:获取选择查找器项,然后将
Get Select Finder items
操作拖到画布区域.
In the search field type: Get Select Finder items and drag the
Get Select Finder items
action into the canvas area.
在搜索字段中键入:运行Shell 并将Run Shell Script
操作拖到画布区域.
In the search field type: Run Shell and drag the Run Shell Script
action into the canvas area.
按如下所示配置Run Shell Script
操作的顶部:
Configure the top part of the Run Shell Script
action as follows:
将以下Bash脚本添加到Run shell Script
操作的主要区域:
Add the following Bash script to the main area of the Run shell Script
action:
#!/usr/bin/env bash
# The following characters are considered impermissible in a basename:
#
# - Left Square Bracket: [
# - Right Square Bracket: ]
# - Left Parenthesis: (
# - Reverse Solidus: \
# - Colon: :
# - Quotation Mark "
# - Single Quotation Mark '
# - Asterisk *
# - Question Mark ?
# - Less-than Sign <
# - Greater-than Sign >
# - Vertical Line |
# - Plus Sign +
# - Space Character
# - UnderScore _
#
# 1. Sed is utilized for character replacement therefore characters listed
# in the bracket expression [...] must be escaped as necessary.
# 2. Any forward slashes `/` in the basename are substituted by default with
# a Colon `:` at the shell level - so it's unnecessary to search for them.
#
declare -r IMPERMISSIBLE_CHARS="[][()\\:\"'*?<>|+_ ]"
declare -r REPLACEMENT_STRING="-"
# Obtain the POSIX path of each selected item in the `Finder`. Input must
# passed to this script via a preceding `Get Selected Finder Items` action
# in an Automator Services workflow.
declare selected_items=("$@")
declare -a sorted_paths
declare -a numbered_paths
# Prefix the POSIX path depth level to itself to aid sorting.
for ((i = 0; i < "${#selected_items[@]}"; i++)); do
numbered_paths+=("$(echo "${selected_items[$i]}" | \
awk -F "/" '{ print NF-1, $0 }')")
done
# Sort each POSIX path in an array by descending order of its depth.
# This ensures deeper paths are renamed before shallower paths.
IFS=$'\n' read -rd '' -a sorted_paths <<< \
"$(printf "%s\\n" "${numbered_paths[@]}" | sort -rn )"
# Logic to perform replacement of impermissible characters in a path basename.
# @param: {Array} - POSIX paths sorted by depth in descending order.
renameBaseName() {
local paths=("$@") new_basename new_path
for path in "${paths[@]}"; do
# Remove numerical prefix from each $path.
path="$(sed -E "s/^[0-9]+ //" <<< "$path")"
# Replaces impermissible characters in path basename
# and subsitutes uppercase characters with lowercase.
new_basename="$(sed "s/$IMPERMISSIBLE_CHARS/$REPLACEMENT_STRING/g" <<< \
"$(basename "${path}")" | tr "[:upper:]" "[:lower:]")"
# Concatenate original dirname and new basename to form new path.
new_path="$(dirname "${path}")"/"$new_basename"
# Only rename the item when:
# - New path does not already exist to prevent data loss.
# - New basename length is less than or equal to 255 characters.
if ! [ -e "$new_path" ] && [[ ${#new_basename} -le 255 ]]; then
mv -n "$path" "$new_path"
fi
done
}
renameBaseName "${sorted_paths[@]}"
您的Automator Service/工作流程的完整画布区域现在应显示如下:
The completed canvas area of your Automator Service/Workflow should now appear something like this:
键入⌘S,或从菜单栏中选择File
> Save
.我们将文件命名为Replace Impermissible Chars
.
Type ⌘S, or choose File
> Save
from the Menu bar. Let's name the file Replace Impermissible Chars
.
运行服务:
-
在 Finder 中:
- 选择一个单个文件或文件夹,然后 ctrl + 单击以显示上下文菜单
- 在上下文菜单中选择
Replace Impermissible Chars
服务以运行它.
- Select a single file or folder and then ctrl+click to show the contextual menu
- Select the
Replace Impermissible Chars
service in the contextual menu to run it.
或者,在 Finder 中:
- 选择多个文件和/或文件夹,然后 ctrl + 单击以显示上下文菜单
- 在上下文菜单中选择
Replace Impermissible Chars
服务以运行它.
- Select multiple files and/or folders and then ctrl+click to show the contextual menu
- Select the
Replace Impermissible Chars
service in the contextual menu to run it.
注意:
-
Finder 将允许在一次选择的多达1000个文件/文件夹上运行服务.
The Finder will allow the Service to be run on up to 1000 files/folders selected at once.
如果这是您创建的第一个Automator Service,则可能(如果我没有记错的话)需要重新启动计算机,以使其可以通过上下文弹出窗口使用菜单.
If this is the first Automator Service you have created you may (if I've remembered correctly!) need to restart your computer for it to become available via the contextual pop-up menu.
如果满足以下两个条件之一,则Bash Shell脚本不会替换文件/文件夹名称中的不允许字符:
The Bash Shell script will not replace impermissible characters in a file/folder name if either of the following two conditions are met:
-
如果已经存在与生成的新文件/文件夹名称匹配的文件/文件夹名称.例如:假设我们有一个名为
hello-world.txt
的文件,在同一个文件夹中有一个名为hello?world.txt
的文件.如果我们在hello?world.txt
上运行服务,则其名称将不会被更正/更改,因为这可能会覆盖已经存在的hello-world.txt
文件.
If a file/folder name already exists which matches the name of a resultant new file/folder name. For example: Let's say we have a file named
hello-world.txt
and in the same folder a file namedhello?world.txt
. If we run the Service onhello?world.txt
, it's name will not be corrected/changed as this would potentially overwrite thehello-world.txt
file which already exists.
如果生成的文件名为>=
,则为255个字符.当然,仅当您将REPLACEMENT_STRING
值(在Bash/Shell脚本中)更改为多个字符而不是一个连字符-
时,才会发生这种情况.
If the resultant file name is >=
to 255 characters. This may of course only occur if you were to change the REPLACEMENT_STRING
value (in the Bash/Shell script) to more than one character, instead of just a single hyphen -
.
这篇关于使用AppleScript用短划线替换文件名中的无效字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!