Magicsheet logo

Transpose File

Medium
12.5%
Updated 8/1/2025

Asked by 1 Company

Topics

Transpose File

What is this problem about?

The "Transpose File coding problem" is a unique shell scripting challenge. You are given a text file file.txt containing a matrix-like structure of words separated by spaces. Your goal is to transpose the contents of the file, such that rows become columns and columns become rows. For example, if the first line has 3 words, the resulting file should have 3 lines, each containing the words that were originally in the same column.

Why is this asked in interviews?

This "Transpose File interview question" is typically asked for DevOps, SRE, or backend roles where data manipulation on the command line is frequent. Companies like Meta use it to test a candidate's proficiency with standard Unix utilities like awk, sed, or tr. It evaluates whether you can solve a data transformation problem concisely using pipes and scripting rather than writing a full-blown program in a language like Python or Java.

Algorithmic pattern used

The "Shell interview pattern" for this problem almost always involves the awk command. Since the number of columns might not be known beforehand, awk is ideal because it can handle field-based processing across multiple lines. We can use an associative array in awk to store the words indexed by their column number and then print them out in the END block. This allows us to process the file in a single pass.

Example explanation

Input file:

name age
alice 21
ryan 30

Processing with awk:

  1. Line 1: col[1]="name", col[2]="age"
  2. Line 2: col[1]="name alice", col[2]="age 21"
  3. Line 3: col[1]="name alice ryan", col[2]="age 21 30" Final Output:
name alice ryan
age 21 30

This transformation is done by concatenating strings for each column index as we read each line.

Common mistakes candidates make

A common mistake in the "Transpose File coding problem" is forgetting to handle trailing spaces or not accounting for varying numbers of columns (though the problem usually guarantees a consistent number). Another error is trying to use sed for a task that is much better suited for awk. Candidates might also struggle with the syntax of loops and arrays within a single-line awk command.

Interview preparation tip

To master the "Shell interview pattern," learn the "Big Three" of Unix text processing: grep, sed, and awk. Specifically for transposition and data formatting, awk is the most powerful tool. Practice using it to print specific columns, sum values, and perform simple string manipulations.

Similar Questions