从列中提取子字符串,并使用 bash 添加新列

发布于 2025-01-20 05:35:17 字数 392 浏览 3 评论 0原文

抱歉,如果是重新发布。

我的数据(在选项卡中的划界文本文件中):

Number  Description
1   YR=2020 Country=country_A ID=QWE
2   YR=2020 ID=ASD
3   YR=2019 Country=country_B ID=ZXC
4   Country=country_C ID=POI

我想使用bash从Description> Description列提取信息。

所需的输出:

Number  YR  ID
1   2020    QWE
2   2020    ASD
3   2019    ZXC
4   -   POI

Sorry if it is a repost.

My data (in a tab delimited text file):

Number  Description
1   YR=2020 Country=country_A ID=QWE
2   YR=2020 ID=ASD
3   YR=2019 Country=country_B ID=ZXC
4   Country=country_C ID=POI

I would like to extract the information from the description column using bash.

Desired output:

Number  YR  ID
1   2020    QWE
2   2020    ASD
3   2019    ZXC
4   -   POI

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

西瑶 2025-01-27 05:35:17

一个awk想法:

awk '
BEGIN  { OFS="\t" }                                  # set output field delimiter as tab
FNR==1 { print "Number","YR", "ID"; next }           # print header, skip to next input line
       { yr=id="-"                                   # init variables for new line
         for (i=2;i<=NF;i++) {                       # loop through space-delimited fields
             if ($i ~ /^YR=/) yr=substr($i,4)        # save everything after the "="
             if ($i ~ /^ID=/) id=substr($i,4)        # save everything after the "="
         }
         print $1,yr,id                              # print new line
       }
' input

注意:删除# comments ...以整理代码

这会生成:

Number  YR      ID
1       2020    QWE
2       2020    ASD
3       2019    ZXC
4       -       POI

One awk idea:

awk '
BEGIN  { OFS="\t" }                                  # set output field delimiter as tab
FNR==1 { print "Number","YR", "ID"; next }           # print header, skip to next input line
       { yr=id="-"                                   # init variables for new line
         for (i=2;i<=NF;i++) {                       # loop through space-delimited fields
             if ($i ~ /^YR=/) yr=substr($i,4)        # save everything after the "="
             if ($i ~ /^ID=/) id=substr($i,4)        # save everything after the "="
         }
         print $1,yr,id                              # print new line
       }
' input

NOTE: remove # comments ... to declutter code

This generates:

Number  YR      ID
1       2020    QWE
2       2020    ASD
3       2019    ZXC
4       -       POI
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文