无法从 awk 命令获取*仅*所需的输出

问题描述 投票:0回答:1

我正在尝试使用 awk 解析文件以在 applescript 中返回 4 个参数的数组,但没有得到所需的结果。

这是 awk 命令:

awk -F '%' '{if ($1=="Actions") print ($2 "," $3 "," $4 "," $5)}' "/Users/<my_username>/Desktop/windowInfo.txt"

这是文件的内容:

Actions%3773%22%1347%699
Transport%3431%1199%665%97
Undo History%3431%1276%665%164

我能做的最好的事情就是获取我想要的用逗号分隔的 4 个参数,但它总是另外返回换行符后下一行的第一个参数。即使我使用

awk -F '%|\n'
将换行符作为分隔符,它仍然返回与换行符上的下一行的第一个参数相同的结果。

我得到的输出示例:

3773,22,1347,699
Transport

我不明白我在这里做错了什么。请帮忙!

对于上下文,我尝试使用以下语法从 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
bash shell awk applescript
1个回答
0
投票

在 Unix/Linux 机器上,名义文件以

\n
结尾。在 MacOS 上,它们以
\r
结尾。在 Windows 机器上,他们使用
\r\n
。由于 awk 有一个默认的记录分隔符
\n
,它只能找到一条记录,即完整文件。

要解决您的问题,您必须添加:

awk 'BEGIN{RS=ORS="\r";FS="%"; OFS=","}($1=="Actions"){print $2,$3,$4,$5}' /path/to/file
© www.soinside.com 2019 - 2024. All rights reserved.