Shell新手求助:如何用指定工具将文件的列追加到另一文件?
Hey there! Let's break down what's going on here and fix your issue.
First, why your current command isn't working: (cat fileA && cat fileB) > fileC just dumps all of fileA's content first, then all of fileB's content after it. So if fileA has a line like 1 2 3 and fileB has 1 2 3, fileC would end up as:
1 2 3 1 2 3
Which is totally not what you want—you need to merge corresponding columns from each line of the two files.
Since you're limited to grep, cut, join, cat, regex, for, and while, here's a straightforward solution using a while loop to read both files line-by-line and interleave their columns:
# Open fileA and fileB in separate file descriptors to read lines in sync exec 3<fileA exec 4<fileB # Read one line from each file at the same time while read -r lineA <&3 && read -r lineB <&4; do # Split each line into arrays of individual columns columnsA=($lineA) columnsB=($lineB) # Build the merged line by pairing corresponding columns from each file merged_line="" for ((i=0; i<${#columnsA[@]}; i++)); do merged_line="$merged_line ${columnsA[$i]} ${columnsB[$i]}" done # Print the merged line (trim the leading extra space) echo "${merged_line# }" done > fileC # Clean up the open file descriptors exec 3<&- exec 4<&-
Let's test this with your example:
- fileA content:
1 2 3 - fileB content:
1 2 3 - The script reads both lines, splits them into arrays
[1,2,3]and[1,2,3], then loops through each index to build1 1 2 2 3 3—exactly the output you're expecting.
If you ever need to just append all columns from fileB's line to the end of fileA's line (e.g., 1 2 3 1 2 3 instead of the interleaved version), you can simplify the loop section to a single line:
echo "$lineA $lineB"
A quick note: this assumes each line in fileA and fileB has the same number of columns. Since you mentioned the files have the same number of rows, I'm guessing this column match holds true for your use case.
内容的提问来源于stack exchange,提问作者user10143594

