使用awk数组实现行转列,生成指定列结构文件求助
Solution to Pivot Data into Columnar Format
Got it, let's figure out how to turn your three files into the columnar.txt you need—even when new medicines get added later on. The best tool for this job is awk, since it's great at handling text manipulation and dynamic data structures.
Here's a reusable script that handles all your requirements:
Save this as pivot_med_data.awk:
#!/usr/bin/awk -f # First, gather all medicines from medicine.txt and dates from data.txt BEGIN { # Load medicine list (skip the separator line) while ((getline < "medicine.txt") > 0) { if ($0 !~ /^=======/) { meds[++total_meds] = $0 med_col[$0] = total_meds } } close("medicine.txt") # Load ordered dates (skip the separator line) while ((getline < "data.txt") > 0) { if ($0 !~ /^====/) { dates[++total_dates] = $0 date_pos[$0] = total_dates } } close("data.txt") } # Process the dynamic movimenta.txt to map date+time to medicine values NR > 2 { # Skip header and separator lines date_key = $1 " " $2 value_map[date_key][$3] = $4 } # Generate the final columnar output END { # Print the header row printf "data" for (i=1; i<=total_meds; i++) { printf " %s", meds[i] } printf "\n" # Print each date's values in the order from data.txt for (i=1; i<=total_dates; i++) { current_date = dates[i] printf "%s", current_date for (j=1; j<=total_meds; j++) { current_med = meds[j] # Use 0 for missing values, or replace with "" if you prefer empty printf " %s", (value_map[current_date][current_med] ? value_map[current_date][current_med] : 0) } printf "\n" } }
How to use this:
- Make the script executable:
chmod +x pivot_med_data.awk - Run it against your
movimenta.txtfile, and redirect the output tocolumnar.txt:./pivot_med_data.awk movimenta.txt > columnar.txt
Why this works for dynamic data:
- Automatic new medicine support: If you add
m4orm5tomedicine.txtlater, the script will automatically include them as new columns in the output—no need to modify the code. - Preserves date order: The output follows the exact order of dates from
data.txt, so your rows stay consistent with the grouped dates you already have. - Handles missing values: If a medicine doesn't have a value for a specific date, it will print
0(you can swap that with an empty string by changing0to""in the script if that's what you need).
内容的提问来源于stack exchange,提问作者Paulo
相关产品推荐
相关产品推荐

