使用AWK将单列文件转换为5列表格的技术实现
Got it, here's a straightforward AWK script that will take your input file with consecutive 5-line blocks and convert each block into a single row with 5 columns (tab-separated by default, which works great for sorting and spreadsheet tools).
The AWK Script
awk ' { # Store each line in an array, using modulo 5 to cycle through indices 0-4 lines[NR % 5] = $0 } # When we reach every 5th line, print the collected block as a single row NR % 5 == 0 { print lines[1] "\t" lines[2] "\t" lines[3] "\t" lines[4] "\t" lines[0] # Clear the array to prepare for the next block delete lines } # Handle any leftover lines if the total isn't a multiple of 5 END { if (NR % 5 != 0) { for (i = 1; i <= NR % 5; i++) { printf "%s\t", lines[i] } if (lines[0]) printf "%s", lines[0] print "" } } ' input.txt > output.txt
How It Works
- Storing Lines:
lines[NR % 5] = $0uses the current line number (NR, an AWK built-in variable) modulo 5 to assign each line to a slot in thelinesarray. This cycles through indices 0 to 4 for every block of 5 lines. - Printing Blocks: When we hit the 5th, 10th, 15th, etc. line (
NR % 5 == 0), we print all 5 stored lines separated by tabs. Note that the 5th line ends up inlines[0], so we print indices 1-4 first, then 0. - Handling Leftovers: The
ENDblock catches any remaining lines if your input doesn't end on a multiple of 5, ensuring no data gets dropped.
Example Input/Output
Input
/* ALPSGAAKO1ZRDCDTNINF3-A-2-O1_ATLNGAMQO1ZSADDTNINF1-A-1-O1 /
ALPSGA_ATLNGA_0 {
srlg-value 1000;
srlg-cost 10000;
}
/ ALPSGAAKO1ZRDCDTNINF3-A-2-O1_MACNGAHRO1ZRDCDTNINF1-A-1-O1 */
ALPSGA_MACNGA_0 {
srlg-value 2000;
srlg-cost 10000;
}
Output (tab-separated)
/* ALPSGAAKO1ZRDCDTNINF^3-A-2-O1_ATLNGAMQO1ZSADDTNINF^1-A-1-O1 */ ALPSGA_ATLNGA_0 { srlg-value 1000; srlg-cost 10000; } /* ALPSGAAKO1ZRDCDTNINF^3-A-2-O1_MACNGAHRO1ZRDCDTNINF^1-A-1-O1 */ ALPSGA_MACNGA_0 { srlg-value 2000; srlg-cost 10000; }
Customization Tip
If you prefer a different separator (like commas for CSV), just replace all instances of "\t" with your desired separator (e.g., ", "). Once converted, you can easily sort the output with sort output.txt or open it in Excel/Google Sheets for comparison.
内容的提问来源于stack exchange,提问作者user3746195

