Puzzleshot #030 - Potluck Leftovers

raw data→awk→result

Thanksgiving is tomorrow. Aunt Linda has emailed you the potluck signup sheet, exported from her old Windows laptop, and you need the list of guests who have confirmed.

potluck.csv:

name,dish,servings,confirmed
Aunt Linda,Green Bean Casserole,12,Y
Uncle Bob,Turkey,20,Y
Grandma Pat,Pumpkin Pie,8,Y
Cousin Dave,Pie,8,N
...

You run:

awk -F, '$4=="Y"' potluck.csv

Nothing comes back. No error, no output. Everyone says they’ve confirmed. awk says nobody’s coming.

Two questions:

Download sample data

Reveal solution

The short version: the file came from Windows, where every line ends in two characters, a carriage return and a newline (\r\n). awk only splits lines on the newline, so the \r is left over, attached to the last column. Column 4 isn’t Y, it’s Y followed by an invisible \r, and “Y” doesn’t equal “Y\r”.

Round 1 - spot it:

cat -A potluck.csv

cat -A shows the invisible characters. Every line ends in ^M$, where ^M is the carriage return and $ marks the end of the line. A normal Unix file would end in just $.

A second tell:

awk -F, 'NR>1 {print length($4)}' potluck.csv

Y and N are one character, but all ten rows print 2.

Why only column 4? The \r sits at the end of the line, so it’s glued to the last column. A filter on an earlier column works fine: awk -F, ‘$2==“Turkey”’ potluck.csv returns Uncle Bob’s row. That’s why the file seems fine until you filter on the last column.

Round 2 - two fixes:

1. Strip the carriage returns, then filter:

tr -d '\r' < potluck.csv | awk -F, '$4=="Y"'

2. Strip them inside awk:

awk -F, '{sub(/\r$/,"")} $4=="Y"' potluck.csv

Both return the seven confirmed guests, with no ^M left on the output lines.

Bonus - clean it once:

tr -d '\r' < potluck.csv > potluck_clean.csv

Write to a new file. If you redirect back into potluck.csv, the shell empties the file before tr gets to read it.

The things to consider:

Why did cat look normal? A terminal treats the \r as “go back to the start of the line”, then the newline moves down, so you never see it.

Could you have matched around it? Yes, $4~/^Y/ also found all seven in my test. But that hides the problem. The \r is still in the data, and it will bite you later when you print, compare or join on that column.

What else would it break? Anything that treats a line as plain text: awk, cut, sort and friends all keep the \r as ordinary data. The header would be wrong too, “confirmed” with a \r on the end.

What would you check on every file from an unknown source? cat -A potluck.csv | head, to see what’s really in there.

The takeaway:

If a filter on the last column finds nothing, look for characters you can’t see.