在 Applescript 中写入 CSV(使用终端 shell)

Writing on a CSV in Applescript (Using terminal shell)

只是想写入我从对话框中选择的 CSV 文件。出于某种原因,这不起作用。谁能帮我吗?谢谢!

set theFile to (choose file)
do shell script "awk -F, ' ~ /Line 2/{=\"hello\"} 1'  & quoted form of POSIX path of theFile & > /tmp/a"

编辑: 我只想写在特定 row/column 上的选定 CSV 上(在本例中为第 2 行,第 22 列)。目前它没有抛出任何错误,但也没有写入所选的 CSV,显示输出 "" –

我认为这里使用quoted form是错误的。您必须打断 AppleScript 字符串并将其添加到您的字符串部分之间。试试这个:

set theFile to (choose file)
do shell script "awk -F, ' ~ /Line 2/{=\"hello\"} 1' " & quoted form of POSIX path of theFile & " > /tmp/a"

如果您的 shell 命令的其余部分没问题,应该会修复它...

玩得开心,迈克尔/汉堡

您的命令将 awk 命令的输出写入“tmp 中名为“a”的文件" 文件夹(这个文件夹是隐藏的),所以 do shell script 的输出是 ""

您的命令编辑第一个字段的内容等于“第 2 行”的行。

  • 要编辑第二行,请使用 NR==2

    要编辑第 1 行到第 5 行,请使用 NR<6

    要编辑第 10 行到第 15 行,请使用 NR>9 && NR<16

Standard awk on OS X 无法就地编辑文件,因此您必须将输出写入临时文件文件并使用 mv 命令覆盖原始文件,但它可能与 GNU awk 4.1.0... --> gawk -i inplace


要编辑某个文件的第二行(以 CSV 文件结尾的行必须是换行符),请使用:

set theFile to quoted form of POSIX path of (choose file)
set tempFile to theFile & ".tmp123"
do shell script "awk -F, 'NR==2{=\"hello\";}1' OFS=, " & theFile & " >" & tempFile & "&& mv -f " & tempFile & " " & theFile

如果以 CSV 文件结尾的行是回车 return,请使用:

do shell script "awk -F, 'NR==2{=\"hello\";}1' RS='\r' ORS='\r' OFS=, " & theFile & " >" & tempFile & "&& mv -f " & tempFile & " " & theFile

更新

这是一个如何将 AppleScript 变量 (m) 放入命令中的示例。

set m to 6 -- a number
do shell script "awk -F, 'NR<" & m & "{=\"hello\";}1' RS='\r' ORS='\r' OFS=, " & theFile & " >" & tempFile & "&& mv -f " & tempFile & " " & theFile

如果您的主要意图确实是 运行 一个 bash+awk 脚本,您可以反过来做...

与其从 Applescript 开始并尝试 运行 shell 和 awk,不如从 shell 开始并调用 Applescript 来选择一个文件,然后在shell和运行awk中进行。

像这样:

#!/bin/bash
file=$( osascript -e 'set theFile to (POSIX path of (choose file))' )
awk '1' "$file"

因此,您得到一个调用 Applescript 的 bash 脚本,而不是调用 bash.

的 Applescript

请注意 1awk 脚本中为真,因此 awk 将只执行其默认操作,即打印当前行 - 显然您可以自己设置awk 命令在那里。