通过 OS X 命令行显示/隐藏文件扩展名

通过 OS X 命令行显示/隐藏文件扩展名

我正在寻找一种通过终端来更改特定文件的扩展名是否显示在 Finder 中的方法,类似于:

$ hideextension ~/music/somesong.mp3

无需打开获取信息并更改复选框,因为它非常繁琐。

我计划将其合并到我使用 FastScripts 通过快捷方式调用的脚本中。我想尝试远离 GUI 脚本,因为感觉不太干净,尽管任何关于如何实现这一点的想法都是受欢迎的。

答案1

通过 GUI 更改此设置的唯一真正方法是单击隐藏扩展在 Finder 中信息窗口。选中此项会更改com.apple.FinderInfo扩展属性,通常无法编辑该属性 - 至少不容易。但是,我们可以使用工具来为我们完成此操作。

为了使下面的工作正常进行,你显然需要显示所有文件扩展名在 Finder 的偏好设置中未选中。


通过 AppleScript

AppleScript 通过命令提供此功能 set extension hidden。显然,您需要alias一个文件对象。例如,我们可以通过对话框获取它。这只是一个最小的工作示例。

tell application "Finder"
    set some_file to (choose file)
    set extension hidden of some_file to true
end tell

要反转,只需truefalse此处交换即可。完整的调用如下,例如:

set extension hidden of alias "Macintosh HD:Users:werner:Desktop:file.png" to true

您也可以直接从脚本文件运行它(谢谢@DanielBeck为补充):

on run argv
tell application "Finder" to set extension hidden of (POSIX file (first item of argv) as alias) to true
end run

将其保存为filename.scpt并从命令行运行:

osascript filename.scpt targetfile

使用SetFile命令

笔记:从 Xcode 6 开始此功能已弃用。

如果您已经安装了 Xcode,您将获得SetFile(1)二进制文件,它可以完全满足您的要求(并提供一些与文件属性相关的功能):

隐藏扩展名:

SetFile -a E <file>

再次显示扩展名:

SetFile -a e <file>

答案2

谢谢響克 感谢您的回答,它帮助我做了我想做的事。

因为我喜欢快捷方式,所以我通过 Automator 创建了一个“运行 Shell 脚本”服务:

for f in "$@"
do
    STATUS=`getFileInfo -ae "$f"`
    if [ $STATUS== 0 ];
    then
        SetFile -a E "$f"
    else
        SetFile -a e "$f"
    fi
done

然后在 Finder -> 服务偏好设置中,我添加了该服务的快捷方式。

Command++对我Shift来说H不起作用,并且Command+H隐藏了应用程序。我选择了Command++ 。ShiftE

答案3

如果您想显示当前隐藏的文件扩展名,还有一个选项:Finder 将此“隐藏扩展名”选项存储在com.apple.FinderInfo扩展文件属性中。您可以通过运行列出所有扩展属性的此命令自行检查:

xattr -l /path/to/the/file

因此,为了显示扩展,您可以删除该属性:

xattr -d com.apple.FinderInfo /path/to/the/file

但请记住,Finder存储其他元数据例如标签颜色等,因此这些元数据将会丢失。而且,由于该属性是二进制的,因此您无法轻易修改它。

答案4

即使SetFile自 Xcode 6 以来已被弃用,但它在 XCode 11 中仍然可用,因此您可以预期它在可预见的未来仍将保留在命令行工具中……

https://download.developer.apple.com/Developer_Tools/Command_Line_Tools_for_Xcode_11/Command_Line_Tools_for_Xcode_11.dmg

$ pkgutil --payload-files /Volumes/Command\ Line\ Developer\ Tools/Command\ Line\ Tools.pkg | grep SetFile
./Library/Developer/CommandLineTools/usr/bin/SetFile
./Library/Developer/CommandLineTools/usr/share/man/man1/SetFile.1

相关内容