You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript如何将两个列表分别写入CSV的独立列?

目录大小导出CSV功能修复方案

原有代码问题

  • 重复执行2次du -sh扫描目标目录,扫描间隙如果目录内文件发生增删、大小变动,会导致文件大小和路径行错位
  • paste命令需要从两个独立输入流/文件读取内容做列合并,直接将多行字符串拼接到命令参数中,会被paste识别为待读取的文件路径,无法完成合并逻辑
  • 未对路径中包含的空格、逗号、特殊字符做CSV格式兼容处理,会导致生成的CSV打开后列错位
  • do shell script是AppleScript原生调用,不需要嵌套在tell application "Finder"块内执行
  • 拼接shell命令时未对路径参数做转义,路径含特殊字符时会直接执行报错

最简实现代码(推荐)

不需要拆分大小、路径为两个独立变量,单次调用du即可完成格式转换直接输出CSV,效率最高不会出现错位问题:

-- 注意:使用前需确保RootDirectoryAlias已提前赋值为目标目录的别名对象
set RootDirectoryPosix to POSIX path of RootDirectoryAlias
do shell script "du -sh -- " & quoted form of RootDirectoryPosix & "*" & " | awk '
BEGIN {FS=\"\\t\"; OFS=\",\"}
{
    gsub(/\"/, \"\\\"\\\"\", $2)
    if ($2 ~ /[, \"]/) $2 = \"\\\"\" $2 \"\\\"\"
    print $1, $2
}
' > ~/Test.csv"

保留双变量逻辑的实现代码

如果业务逻辑必须单独存储ChildSizes、ChildPaths两个列表变量,可通过临时文件传递内容给paste处理,执行完成后自动清理临时文件:

-- 注意:使用前需确保RootDirectoryAlias已提前赋值为目标目录的别名对象
set RootDirectoryPosix to POSIX path of RootDirectoryAlias
set duRawOutput to do shell script "du -sh -- " & quoted form of RootDirectoryPosix & "*"
set ChildSizes to do shell script "printf '%s\\n' " & quoted form of duRawOutput & " | cut -f1"
set ChildPaths to do shell script "printf '%s\\n' " & quoted form of duRawOutput & " | cut -f2"

set tmpSizePath to POSIX path of (path to temporary items) & "child_size_tmp.txt"
set tmpPathList to POSIX path of (path to temporary items) & "child_path_tmp.txt"

do shell script "printf '%s\\n' " & quoted form of ChildSizes & " > " & quoted form of tmpSizePath
do shell script "printf '%s\\n' " & quoted form of ChildPaths & " > " & quoted form of tmpPathList

do shell script "paste -d , " & quoted form of tmpSizePath & " " & quoted form of tmpPathList & " | awk -F, '
{
    filePath = substr($0, index($0, \",\")+1)
    gsub(/\"/, \"\\\"\\\"\", filePath)
    if (filePath ~ /[, \"]/) filePath = \"\\\"\" filePath \"\\\"\"
    print $1 \",\" filePath
}
' > ~/Test.csv; rm -f " & quoted form of tmpSizePath & " " & quoted form of tmpPathList

代码中所有传入shell的变量都用quoted form of做了转义处理,兼容路径含空格、特殊字符的场景,符合CSV字段转义规范,生成的文件可直接被Excel、Numbers等表格工具正常打开。

内容的提问来源于stack exchange,提问作者dxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 15:51:22