Reputation: 1519
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)?
Upvotes: 0
Views: 310
Reputation: 360105
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
Upvotes: 1
Reputation: 15345
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()
}
}
Upvotes: 0