简体   繁体   中英

Linux awk Columns Comparison

I have data that looks like this:

    0 1 0 0
    0 0 0 1
    0 0 0 1
    0 1 0 0

I want to print all directly subsequent rows with 1s in the same column, using awk. How would I do this?

EDIT:

Is there no way within awk to specify the previous column, something like "$1-1" (I know thats wrong btw)?

This is overly simplistic, but it will work with your sample data:

awk '$0 == prev {print} {prev = $0}' inputfile

If you want to print both lines (which are identical):

awk '$0 == prev {print; print} {prev = $0}' inputfile

or

awk '$0 == prev {print prev; print} {prev = $0}' inputfile

I assumed that there is exact one 1 per line. Further assuming your data is in data.input.

usage:

awk -f foo.awk data.input

foo.awk:

function printBlock() {
    for(i=0; i<N; i++) {
        print BLOCK[i];
    }
}

{
    for(col=1; col<=NF; col++) {
        if($col==1) break;
    }
    if(col != last_col) {
        if(N > 1) {
            printBlock()
        }
        N = 0
    }
    BLOCK[N++] = $0;
    last_col = col;
}

END {
    if(N > 1) {
        printBlock()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM