【问题标题】:Transform delimited fields to lines with name and value将分隔字段转换为具有名称和值的行
【发布时间】:2022-01-20 04:54:18
【问题描述】:

文件 a 包含字段名称:

timestamp,name,ip

文件 b 包含值:

2021-12-17 16:01:19.970,app1,10.0.0.0
2021-12-17 16:01:19.260,app1,10.0.0.1

当我使用 awk 时如下:

awk 'BEGIN{FS=",";OFS="\n"} {if(NR%3==0){print "----"};$1=$1;print;}' b

我明白了:

----
2021-12-17 16:01:19.970
app1
10.0.0.0
----
2021-12-17 16:01:19.260
app1
10.0.0.1

有什么方法可以在每一行中合并 key:value 吗? 我想要的输出是:

----
timestamp:2021-12-17 16:01:19.970
app:app1
ip:10.0.0.0
----
timestamp:2021-12-17 16:01:19.260
app:app1
ip:10.0.0.1

【问题讨论】:

    标签: shell awk


    【解决方案1】:

    使用您展示的示例,请尝试关注awk 程序。

    awk '
    BEGIN{ FS="," }
    FNR==NR{
      for(i=1;i<=NF;i++){
        heading[i]=$i
      }
      next
    }
    {
      print "----"
      for(i=1;i<=NF;i++){
        print heading[i]":"$i
      }
    }
    ' filea fileb
    

    说明:为上述添加详细说明。

    awk '                     ##Starting awk program from here.
    BEGIN{ FS="," }           ##Stating BEGIN section of this program and set FS to , here.
    FNR==NR{                  ##Checking condition which will be TRUE when filea is being read.
      for(i=1;i<=NF;i++){     ##Traversing through all fields here.
        heading[i]=$i         ##Setting heading array index as i and value as current field.
      }
      next                    ##next will skip all further statements from here.
    }
    {
      print "----"            ##printing ---- here.
      for(i=1;i<=NF;i++){     ##Traversing through all fields here.
        print heading[i]":"$i ##Printing heading with index i and colon and value of current field.
      }
    }
    ' filea fileb             ##Mentioning Input_file names here.
    

    【讨论】:

    • 所以,如果我有 32 个字段,我应该重复 ORS 标题[1]":"$1?
    • @RickyWu,当然,我已经相应地更改了代码,我们现在不需要硬编码任何东西,你现在可以试试,如果这对你有帮助,请告诉我?
    • 是的,效果很好,谢谢!我们可以将读取标题移动到 BEGIN 中吗?那么我可以更轻松地使用这个脚本与管道一起工作吗?
    • @RickyWu,你的意思是文件头?如果是,则否;文件将永远不会在 BEGIN 部​​分中读取。您在哪个文件中有标题?
    • 任何文件都没有标题,我必须手动准备它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2019-02-18
    • 2021-12-16
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多