This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging
❤ ️ the original ❤ ️
Given a file file.txt, transpose its contents.
You can assume that each column has the same number of columns and that each field is separated by ‘ ‘.
Example:
Assume that the contents of the file. TXT file are as follows:
name age
alice 21
ryan 30
Copy the code
Should output:
name alice ryan
age 21 30
Copy the code
☀️
Analysis of the
The contents of the file are 2 rows and 3 columns, each with the same number of columns. The fields are separated by ‘ ‘. The first column needs to be converted into the first row and the second column into the second row.
Xargs Multiple lines change to single lines
It’s easy to think of xargs as a command to convert single – or multi-line text input to other formats, such as multi-line to single-line, single-line to multi-line.
For example:
cat <<EOF>1.txt
1
2
3
EOF
cat 1.txt | xargs
Copy the code
But there is a problem, if you have multiple columns, the output can only be sequential and can only be a single line. Which is as follows:Can’t achieve the desired effect. So you have to find a way to take each column in turn and execute itxargs
The output.How do I get the first column?
Awk + print Prints columns
You can use the awk command to process the text and configure the print command to get the data for the specified column:
awk '{print $1}' 1.txt
Copy the code
That’s all we need. We just need to get the number of columns in the text and loop through it.
Head + wc gets the number of columns
You can run the head -n command to obtain the specified number of rows in the file, and then run the wc -w command to obtain the number of all columns in the current row. Since we have the same number of rows and rows, we can just take the first row.
cat 1.txt | head -n 1 | wc -w
Copy the code
Get the total number of columns per row as 2. Then write another loop to output:
columns=$(cat 1.txt | head -n 1 | wc -w)
for i in $(seq 1 $columns)
do
awk '{print $'' '$i' ''} ' 1.txt | xargs
done
Copy the code
So far, we have successfully solved the problem and achieved the desired result. The paper1.txt
Switch tofile.txt
, go to LeetCode and see the results:
❄️ at the end ❄️
This topic mainly uses some basic Linux commands, such as awk, head, xargs, wc, and print.
That’s the end of this sharing
If you think the article is helpful to you, like, collect, follow, comment, one key four support, your support is the biggest motivation for my creation.