You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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:

  1. Make the script executable:
    chmod +x pivot_med_data.awk
    
  2. Run it against your movimenta.txt file, and redirect the output to columnar.txt:
    ./pivot_med_data.awk movimenta.txt > columnar.txt
    

Why this works for dynamic data:

  • Automatic new medicine support: If you add m4 or m5 to medicine.txt later, 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 changing 0 to "" in the script if that's what you need).

内容的提问来源于stack exchange,提问作者Paulo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:37:47