Swap and reformat CSV columns
Launch week, Friday: the export reshaped. One slip with five circled columns, tested on one row first, another for cents, and a block with $A for a new column.
Friday of launch week, 9:00 a.m. The accountant, one last time this quarter: the new system wants the order export with the status second, prices in cents instead of dollars, and a currency column at the end. Hundreds of rows; the sample here has eight.
Every row has the same shape, which is exactly what slips and blocks are for.
Warm-up from earlier chapters
Two from earlier chapters, from memory, before the new idea. Two wrong tries show the answer.
Guest, from anywhere inside it.Guest, from anywhere inside it.Circle every column
To reorder columns, circle each one in the pattern and put them back in the new order: ([^,]*) is everything up to the next comma, so five of those circles the five columns, and the replacement \1,\5,\2,\3,\4 moves the fifth to second. In very magic mode (\v), plain brackets circle. For a column that's the same on every line, a block is quicker: Ctrl-v, down, $A.
| circle | \1 | \2 | \3 | \4 | \5 |
|---|---|---|---|---|---|
| column | order_id | item_name | quantity | unit_price | order_status |
| put back | 1st | 3rd | 4th | 5th | 2nd |
2201,al-pastor,1,9.50,delivered2201,delivered,al-pastor,1,9.50A comma in quotes
Another shop's export puts quotes around a name with a comma in it. What does the same slip make of this row?
Stage 1 · The order of the columns
9:10. The last column moves to second place, on every line, header included. First test the slip on one row: the cursor is on the first one, and :s changes only this line. Check that delivered came second. Then undo the test with u and send the same slip to every line with g& (from the Ex chapters: the last slip, to the whole file).
Stuck? Show a hint
:s/\v^([^,]*),([^,]*),([^,]*),([^,]*),(.*)$/\1,\5,\2,\3,\4/<CR> · then u g&This exercise needs a keyboard. Read on, and play it at your computer.
Stage 2 · Cents
9:30. Prices in cents: 9.50 becomes 950 on every row (the price is at the end of each line now), and the header's unit_price becomes price_cents. The header and the rows need different changes.
Stuck? Show a hint
The first exercise of every lesson is free. Pro unlocks the rest, every track, for good.
See ProThis exercise needs a keyboard. Read on, and play it at your computer.
Stage 3 · The currency
9:50. A last column: ,currency on the header, ,USD on every row. The rows end at different lengths.
Stuck? Show a hint
The first exercise of every lesson is free. Pro unlocks the rest, every track, for good.
See ProThis exercise needs a keyboard. Read on, and play it at your computer.
Columns, from memory
Press the keys.