如何删除具有相同 id 字符串的行

MOH*_*MED 1 text-processing

我有以下文件(请注意,它们========实际上存在于文件中):

start ======== id: 5713
start ======== id: 5911
start ======== id: 5911
end ========= id: 5911
start ======== id: 6111
end ========= id: 5713
start ======== id: 31117
Run Code Online (Sandbox Code Playgroud)

我想删除具有相同 id 且分别具有startend的任意两行。

基于上面的例子,输出将是:

start ======== id: 5911
start ======== id: 6111
start ======== id: 31117
Run Code Online (Sandbox Code Playgroud)

如何用bash, awk, sed... 做到这一点?

Ed *_*ton 5

在每个 Unix 机器上的任何 shell 中使用任何 awk,这将打印输入中存在的尽可能多的不成对的开始和/或结束语句:

$ cat tst.awk
$1 == "start" { beg[$NF] = $0; delta =  1 }
$1 == "end"   { end[$NF] = $0; delta = -1 }
{ cnt[$NF] += delta }
END {
    for ( key in cnt ) {
        for (i=1; i<=cnt[key]; i++) {
            print beg[key]
        }
        for (i=-1; i>=cnt[key]; i--) {
            print end[key]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

$ awk -f tst.awk file
start ======== id: 5911
start ======== id: 6111
start ======== id: 31117
Run Code Online (Sandbox Code Playgroud)

为了更好地演示使用更全面的示例输入:

$ cat file
start ======== id: 5713
start ======== id: 5911
start ======== id: 5911
start ======== id: 5911
end ========= id: 5911
start ======== id: 6111
end ========= id: 5713
end ========= id: 5713
start ======== id: 31117
Run Code Online (Sandbox Code Playgroud)

$ awk -f tst.awk file
end ========= id: 5713
start ======== id: 5911
start ======== id: 5911
start ======== id: 6111
start ======== id: 31117
Run Code Online (Sandbox Code Playgroud)