Bash 0194.bash
cat file.txt | awk '{ nf=NF; for (i=1; i<=nf; i++) t[i]=t[i]" "$i } END { for (i=1; i<=nf; i++) print(t[i]) }' | sed "s/^ //"
Difficulty
and has an acceptance rate of about 33% (100k+ submissions).
Typical patterns to solve this problem:
- Shell
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The script processes a text file line-by-line, collects each column across all lines, and finally emits one line per column containing the concatenated values. The pipeline consists of three stages: a cat command that streams the file, an awk program that builds the column strings, and a sed command that removes an unwanted leading space from each output line.
Reading the Input
cat file.txt |
The cat utility opens file.txt and streams its contents to the next stage of the pipeline. By feeding the data through standard output, the script can handle arbitrarily large files without loading the entire file into memory at once. The use of a pipe ensures that each line is processed as soon as it becomes available.
Accumulating Columns with awk
awk '{
nf = NF
for (i = 1; i <= nf; i++)
t[i] = t[i] " " $i
}
END {
for (i = 1; i <= nf; i++)
print(t[i])
}'
The awk program performs the core transformation.
- The variable
nfcaptures the number of fields (NF) on the current line. This value determines how many iterations the inner loop will execute. - The
forloop iterates over each field indexi. For each column, the script appends a space followed by the field value$ito the array elementt[i]. Becauset[i]is initially empty, the first concatenation yields a leading space that is later removed. - The
ENDblock runs after all input lines have been read. It iterates from1tonf-the field count from the last processed line-and prints each accumulated column string stored int[i].
Edge Cases Handled by the awk Stage
When a line contains no fields (for example, an empty line), NF is zero, so nf becomes zero and the inner loop does not execute. This means that empty lines do not disturb the existing column accumulations. If the file ends with a line that has fewer fields than earlier lines, the END block will only print up to the number of fields present in that final line, naturally limiting output to columns that have data in the last record.
Because awk treats any sequence of whitespace as a field separator, lines with irregular spacing are normalized: multiple spaces or tabs between words are collapsed, and leading/trailing whitespace does not generate empty fields. This behavior ensures consistent column alignment regardless of the original spacing.
Trimming the Leading Space with sed
sed "s/^ //"
Each column string built by awk begins with a space due to the concatenation pattern " " $i. The sed substitution command removes that initial space from every line of output. The regular expression ^ matches a space at the start of a line, and the replacement is empty, effectively stripping the unwanted character.
Edge Cases Handled by the sed Stage
If a column string happens to be empty-possible when the input file contains no data-the substitution finds no leading space, leaving the line unchanged (which is an empty line). This behavior gracefully handles the case of an entirely empty input without producing spurious characters.
Performance Optimizations Observed
The script processes the file in a single pass through awk, avoiding multiple reads or temporary storage on disk. By accumulating column data in an in-memory array, it eliminates the need for external sorting or intermediate files. The use of a pipeline ensures that each stage begins work as soon as data becomes available from the previous stage, enabling streaming processing and reducing overall latency.
The awk implementation leverages built-in variables (NF, $i) and simple arithmetic, which are highly optimized in the interpreter. The final sed operation is a lightweight substitution that runs in linear time over the output, adding minimal overhead.
Overall, the combination of streaming input, in-memory accumulation, and a minimal post-processing step results in an efficient solution for transposing columnar data from a text file.
ELI5 - Simplified Explanation
Imagine you have a big stack of building blocks, and on each block, there is a word written. You have lines of blocks, and you want to turn them sideways so that the first word of every line becomes a new column, the second word of every line becomes the next column, and so on.
First, the computer reads your file one line at a time. It keeps a little notebook where it remembers each word it sees, keeping track of which column that word belongs in. It puts all the first words in a row, all the second words in another row, and continues until it has looked at every single word in your file.
Once it reaches the end of your file, it looks at its notebook and prints out all those new rows it built. Because the computer was very careful to add a tiny space before every word while it was building those rows, there is one pesky little empty space at the very start of every line. The last part of the command is like a tiny robot with an eraser that goes through and cleans up those extra spaces at the beginning, leaving you with perfect columns of your words.
Code Quality
Complexity Analysis
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 203: Remove Linked List Elements
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 607: Sales Person
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 192: Word Frequency
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 585: Investments in 2016
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 626: Exchange Seats
- problem 725: Split Linked List in Parts
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality