How to move all strings in one file that match the

2019-09-12 04:59发布

I have two files, each with one column that look like this:

File 1

chr1 106623434
chr1 106623436
chr1 106623442
chr1 106623468
chr1 10699400
chr1 10699405
chr1 10699408
chr1 10699415
chr1 10699426
chr1 10699448
chr1 110611528
chr1 110611550
chr1 110611552
chr1 110611554
chr1 110611560

File 2

chr1 1066234
chr1 106994
chr1 1106115

I want to search file 1 with each line of file 2 and pull out every line that has the exact string and put into a new file. I want each search output to be in its own column or line separated by tabs. I want to do this for every line in file 2. Hopefully the output will look something like this:

chr1 106623434  chr1 10699400   chr1 110611528
chr1 106623436  chr1 10699405   chr1 110611550
chr1 106623442  chr1 10699408   chr1 110611552
chr1 106623468  chr1 10699415   chr1 110611554
                chr1 10699426   chr1 110611560
                chr1 10699448     

标签: unix awk grep
1条回答
2楼-- · 2019-09-12 05:23
$ cat tst.awk
NR==FNR { tgts[++numTgts] = $0; next }
{
    for (tgtNr=1; tgtNr<=numTgts; tgtNr++) {
        tgt = tgts[tgtNr]
        if ($0 ~ "^"tgt) {
            numHits[tgtNr]++
            maxHits = (numHits[tgtNr] > maxHits ? numHits[tgtNr] : maxHits)
            hits[tgtNr,numHits[tgtNr]] = $0
        }
    }
}
END {
    for (hitNr=1; hitNr<=maxHits; hitNr++) {
        for (tgtNr=1; tgtNr<=numTgts; tgtNr++) {
             printf "%-16s%s", hits[tgtNr,hitNr], (tgtNr<numTgts?OFS:ORS)
        }
    }
}

$ awk -f tst.awk file2 file1
chr1 106623434   chr1 10699400    chr1 110611528
chr1 106623436   chr1 10699405    chr1 110611550
chr1 106623442   chr1 10699408    chr1 110611552
chr1 106623468   chr1 10699415    chr1 110611554
                 chr1 10699426    chr1 110611560
                 chr1 10699448
查看更多
登录 后发表回答