Similar Problems
Similar Problems not available
Transpose File - Leetcode Solution
Companies:
LeetCode: Transpose File Leetcode Solution
Difficulty: Unknown
Topics: unknown
The Transpose File problem on LeetCode is a problem that requires the user to write a bash script that transposes the rows and columns of a given file. The file contains delimited fields, and the transposed file should have the delimiter replaced with a space character.
Here is a detailed solution to the Transpose File problem on LeetCode:
Solution
First, we need to create a file named "file.txt" with the input data. For example, the following is the contents of file.txt:
name,age,gender
Alice,25,Female
Bob,30,Male
Charlie,35,Male
The bash command to create file.txt is:
cat << EOT > file.txt
name,age,gender
Alice,25,Female
Bob,30,Male
Charlie,35,Male
EOT
Next, we can use the awk command to transpose the rows and columns of the file. Specifically, we will use the following command:
awk '{
for(i=1;i<=NF;i++){
if(NR==1){
s[i]=$i;
} else {
s[i]=s[i]" "$i;
}
}
} END {
for(i=1;i<=NF;i++){
print s[i];
}
}' file.txt
The awk command works as follows:
- For each line (row) of the input file, we loop through each field (column) by using the
for
loop with a counter variablei
. - If the current row is the first row (e.g.,
NR==1
), then we initialize an arrays
with the current field as the value for thei
-th index of the array. - If the current row is not the first row, then we append the current field to the
i
-th index of thes
array by concatenating a space character and the current field with the previous value of thes
array for that index. - Finally, after reading all the lines of the input file, we loop through each index of the
s
array and print the value of thei
-th index, which now contains the transposed row.
The output of the above command should be:
name Alice Bob Charlie
age 25 30 35
gender Female Male Male
Note that the delimiter (comma) is replaced with a space character. Also note that the first row of the input file becomes the first column of the output file, and vice versa for the other rows.
Transpose File Solution Code
1