使用Awk解析文件时无法仅获取期望输出的问题求助
问题:AppleScript调用Awk解析文件返回多余内容的解决方法
问题描述
我尝试在AppleScript中调用Awk解析文本文件,期望返回包含4个窗口参数的数组,但结果不符合预期。测试用的Awk命令如下:
awk -F '%' '{if ($1=="Actions") print ($2 "," $3 "," $4 "," $5)}' "/Users/<my_username>/Desktop/windowInfo.txt"
执行后虽然能拿到目标的4个逗号分隔参数,但总会额外输出下一行的第一个参数,即使将分隔符改为%|\n也无效。
目标文件内容
Actions%3773%22%1347%699 Transport%3431%1199%665%97 Undo History%3431%1276%665%164
错误输出示例
3773,22,1347,699 Transport
上下文与AppleScript代码
我的需求是匹配窗口名称,从文本文件中获取窗口位置和尺寸数据,用来调整Finder窗口,调用的AppleScript代码如下:
repeat with winName in winNames set shellCommand to "awk -F '%' '{if ($1==\"" & winName & "\") print $2,$3,$4,$5}' " & filePath set {winX, winY, winW, WinH} to (do shell script shellCommand) if (winX is not "") and (winY is not "") and (winW is not "") and (WinH is not "") then tell application process "Finder" set theWindow to (every window whose name is winName) if (count of theWindow) > 0 then set position of theWindow to {winX, winY} set size of theWindow to {winW, WinH} end if end tell end if end repeat
问题原因与解决方法
问题根源
- 引号转义错误:当
winName包含空格(比如"Undo History")时,直接拼接进Awk命令会导致语法错误,使得条件判断失效,Awk可能错误执行print语句或处理后续行。 - 路径未加引号:如果
filePath包含空格,未加引号会导致Awk将路径拆分,处理错误的文件。 - 输出格式不匹配:AppleScript的列表赋值依赖空格/换行作为分隔符,若Awk输出用逗号分隔,会导致赋值失败;同时多余的输出行也会打乱变量赋值。
修复后的代码
repeat with winName in winNames -- 用Awk的-v参数传递变量,避免引号转义问题;给文件路径加引号处理空格 set shellCommand to "awk -F '%' -v target=\"" & winName & "\" '$1 == target {print $2, $3, $4, $5}' \"" & filePath & "\"" set shellOutput to do shell script shellCommand -- 仅当输出非空时才进行变量赋值 if shellOutput is not "" then set {winX, winY, winW, winH} to words of shellOutput tell application process "Finder" set theWindow to (every window whose name is winName) if (count of theWindow) > 0 then -- 将字符串转换为数值,避免AppleScript识别为文本 set position of theWindow to {winX as integer, winY as integer} set size of theWindow to {winW as integer, winH as integer} end if end tell end if end repeat
关键修复点
- 使用
-v target=\"" & winName & "\"将窗口名称作为Awk变量传递,彻底避免拼接字符串时的引号转义问题,确保条件判断$1 == target准确匹配。 - 给
filePath添加双引号,处理路径中包含空格的情况。 - 先将shell输出保存到变量,判断非空后再用
words of shellOutput将输出拆分为列表,确保变量赋值正确。 - 将字符串参数转换为整数,避免AppleScript将其作为文本处理导致窗口调整失败。
内容的提问来源于stack exchange,提问作者Max Well
相关产品推荐
相关产品推荐

