【问题标题】:awk: merge 2 csv files into 1awk:将 2 个 csv 文件合并为 1 个
【发布时间】:2016-02-09 10:21:15
【问题描述】:

文件 1 MNT

title
from:,01.01.2016
to:,31.01.2016
days:,31
employees count:,169.00
counteddays:,206
counteddays KF:,141
counteddays KG:,65
percentage:,3.50%
percentage KF:,2.40%
percentage KG:,1.10%
results on:,08.02.2016

文件 2 年初至今

title
from:,01.01.2016
to:,08.02.2016
days:,39
employees count:,168.62
counteddays:,250
counteddays KF:,172
counteddays KG:,78
percentage:,3.38%
percentage KF:,2.33%
percentage KG:,1.06%
results on:,08.02.2016

我想得到什么:

title, month, ytd

from:,01.01.2016,01.01.2016
to:,31.01.2016,08.02.2016
days:,31,39
employees count:,169.00,168.62
counteddays:,206,250
counteddays KF:,141,172
counteddays KG:,65,78
percentage:,3.50%,3.38%
percentage KF:,2.40%,2.33%
percentage KG:,1.10%,1.06%
results on:,08.02.2016,08.02.2016

在另一个线程上我发现了这样的东西:

awk 'FNR==NR{a[$1]=$2 FS $3;next}{ print $0, a[$1]}' file2 file1

但我无法为我的文件找到正确的语法。

我有一个每月任务,它给了我 2 个上述格式的 csv 文件。 我的任务只是用基本的批处理工具或 awk 以简单的方式合并它们。

编辑:我尝试过的批处理方式,但不起作用:

for /f "tokens=1 delims=," %%a in ('type %MNT% ^| find ","') do (
  for /f "tokens=2 delims=," %%b in ('type %MNT% ^| find "%%a"') do (
    for /f "tokens=2 delims=," %%c in ('type %YTD% ^| find "%%a"') do (
        echo %%a,%%b,%%c >> %RESULT%
    )
  )
)

【问题讨论】:

    标签: awk merge


    【解决方案1】:

    像这样:

    awk -F':' 'NR==FNR{a[NR]=$0;next}{print a[FNR]$2}' mnt ytd
    
    • 标题被忽略。
    • 假设两个文件的行数相同。

    【讨论】:

    • 非常感谢!,你能解释一下语法吗,所以我只是不复制它,也许从中学到一些东西
    • 首先{...}将mnt保存在哈希表中,key是行号。 snd {...} 将 mnt 中的同一行(从哈希表中获取)与 ytd 中的当前行连接起来。然后打印。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    相关资源
    最近更新 更多