linux - 比较字符串并将值连接到 bash shell 中的一个字段中

标签 linux bash awk sed


我正在编写一个脚本来修改 csv 文件

这是我的 csv 文件:

"ID", "Subject" , "Channels", "Description"
"24" , "Bind-0.9.3" , "Linux", "BIND (Berkeley Internet Name Domain) is an implementation of the DNS (Domain Name System) protocols"
"24" , "Bind-0.9.3", "Fedora", "BIND (Berkeley Internet Name Domain) is an implementation of the DNS (Domain Name System) protocols"
"25" , "Tar-8.0.1" , "Debian", "Tar Package"
"25" , "Tar-8.0.1", "Ubuntu" , "Tar Package"

现在,我想比较“ID”值。如果它们的值相同,我们可以将“Channels”加入一个字段

这是预期结果:

"ID", "Subject" , "Channels", "Description"
"24" , "Bind-0.9.3" , "Linux , Fedora", "BIND (Berkeley Internet Name Domain) is an implementation of the DNS (Domain Name System) protocols"
"25" , "Tar-8.0.1" , "Debian , Ubuntu", "Tar Package"

有人知道在我的例子中使用 awk、sed 或其他东西吗?
非常感谢
问候,

最佳答案

$ cat tst.awk
BEGIN { FS="[[:space:]]*,[[:space:]]*"; OFS=" , " }
NR==1 { print; next }
{
    subj[$1] = $2
    desc[$1] = $4
    if ($1 in chans) {
        chans[$1] = chans[$1] OFS $3
    }
    else {
        chans[$1] = $3
        cnt2chan[++numChans] = $1
    }
}
END {
    for (chanNr=1; chanNr<=numChans; chanNr++) {
        chan = cnt2chan[chanNr]
        gsub(/\"/,"",chans[chan])
        print chan, subj[chan], "\"" chans[chan] "\"", desc[chan]
    }
}
$
$ awk -f tst.awk file
"ID", "Subject" , "Channels", "Description"
"24" , "Bind-0.9.3" , "Linux , Fedora" , "BIND (Berkeley Internet Name Domain) is an implementation of the DNS (Domain Name System) protocols"
"25" , "Tar-8.0.1" , "Debian , Ubuntu" , "Tar Package"

关于linux - 比较字符串并将值连接到 bash shell 中的一个字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26332027/

相关文章:

c - 在 Linux 环境下运行的 OSX 终端上编译代码很困难

linux - 如何将 in.mpathd 从 Solaris 移植到 Linux?

linux - 如何在 bash 中的某一行之后对文件进行排序?

bash - 如何使用 awk 按天将带时间戳的日志文件拆分为多个文件

linux - Bash 内置哈希和命令搜索

bash - 在 bash 上处理 az sql db list 的 Azure CLI 输出

linux - 如何在 bash shell 脚本中启动两个线程?

linux - 如何将参数传递给 AWK 中处理的每一行的命令

linux - 在 Shell 中,如何对作为字符串一部分的数字进行算术运算?

linux - 如何在 xemacs 中运行 gdb 以获取交叉编译的代码?