如何在Linux Bash中转换多列表格为指定两列格式?
Solution to Rearrange Key-Value Pairs by Occurrence Order
Got it, let's solve this. The goal is to take a list of repeating key-value pairs and rearrange them so all first occurrences of each key come first, then all second occurrences, and so on.
Here's an awk script that does exactly this—it handles any number of keys/occurrences, plus supports tabs, commas, or spaces as separators:
BEGIN { # Set field separator to handle tabs, commas, or spaces (including mixes) FS = "[,\t ]+" } { # Step 1: Collect values for each key, tracking their occurrence order num_keys = 0 delete count delete vals delete keys for (i = 1; i <= NF; i += 2) { key = $i val = $(i + 1) count[key]++ vals[key][count[key]] = val # Track unique keys in the order they first appear if (!(key in keys)) { keys[++num_keys] = key } } # Step 2: Find the maximum number of occurrences any key has max_count = 0 for (k in count) { if (count[k] > max_count) { max_count = count[k] } } # Step 3: Build output by iterating through each occurrence level output = "" for (level = 1; level <= max_count; level++) { for (k_idx = 1; k_idx <= num_keys; k_idx++) { current_key = keys[k_idx] # Only add if this key has a value at the current level if (level <= count[current_key]) { output = output current_key " " vals[current_key][level] " " } } } # Trim trailing space and print the result sub(/ $/, "", output) print output }
How to Use It
Save the script as rearrange_pairs.awk, then run it against your input file:
awk -f rearrange_pairs.awk input.txt
Or pipe your input directly:
echo "1 0.75 1 0.38 2 0.80 2 0.18" | awk -f rearrange_pairs.awk
Testing with Your Example
Input:
1 0.75 1 0.38 2 0.80 2 0.18
Output:
1 0.75 2 0.80 1 0.38 2 0.18
Which matches exactly what you need!
Notes
- Handles any number of keys and any number of occurrences per key (even if keys have different counts)
- Works with tabs, commas, or spaces as separators (mixes are okay too)
- Preserves the original order of first occurrence of each key
内容的提问来源于stack exchange,提问作者Ravid
相关产品推荐
相关产品推荐

