Search code examples
bashshellawkapplescript

can't get *only* desired output from awk command


I'm trying to parse a file using awk to return an array of 4 arguments in an applescript, but am not getting the desired result.

Here's the awk command:

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

And here's the content of the file:

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

The best I've been able to do is getting the 4 arguments I want separated by commas, but then it always additionally returns the first argument from the next line after a newline. Even when I use awk -F '%|\n' to include the newline as a separator, it's still returning the same result with the first argument of the following line on a newline.

example of the output I'm getting:

3773,22,1347,699
Transport

I can't figure out what I'm doing wrong here. Please help!

For context, I am trying to call this from an applescript using the following syntax to return window position and size data from a text file based on window name matching:

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

Solution

  • On Unix/Linux machines, the nominal files end lines with \n. Where on MacOS they are ending with \r. On windows machines, they use \r\n. Since awk has a default record separator of \n it only finds a single record, which is the full file.

    To solve your issue, you have to add:

    awk 'BEGIN{RS=ORS="\r";FS="%"; OFS=","}($1=="Actions"){print $2,$3,$4,$5}' /path/to/file