i new coding things.i have been trying replace specific elements days.
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 7 4 5 1 2 7 4 5
first want find lines have 7 in 3rd column. if line has 7, want replace 3rd column in 2 above line 0.
((i=n1;i<n1+5;i++)) n2=`grep -n "$i" test.txt | cut -d ':' -f1` let n3=$n2{print $3} awk 'n3==7 (n2-2){print $3=0}' done test < test1
i have totally no idea, need help. thanks
i assume number of fields 5, otherwise adapt script.
give try this:
awk '$3=="7" && nr>2{b[3,1+nr%2]="0"} nr>2{i=1+nr%2;print b[1,i],b[2,i],b[3,i],b[4,i],b[5,i]} {i=1+nr%2;for(j=1;j<=nf;j++) b[j,i]=$j} end {for (i=1;i<=2;i++) print b[1,i],b[2,i],b[3,i],b[4,i],b[5,i]}' text.txt
there exellent tutorial start awk - tutorial , introduction - bruce barnett
this above awk
script using two-dimensional array (b[f,l]
buffer) store fields of 2 previous lines.
each line of script follow pattern {commands}
.
nr
record (line) number. 1+nr%2
alternatively equals 1
, 2
.
$3=="7" && nr>2{b[3,1+nr%2]="0"}
: 3rd field of record (line) nr-2 reseted 0 when current 3rd field equals 7
.
nr>2{i=1+nr%2;print b[1,i],b[2,i],b[3,i],b[4,i],b[5,i]}
: fields of record (line) nr-2 stored in buffer printed starting record numer 3.
{i=1+nr%2;for(j=1;j<=nf;j++) b[j,i]=$j}
: fields of current record (line) saved buffer.
end {for (i=1;i<=2;i++) print b[1,i],b[2,i],b[3,i],b[4,i],b[5,i]}
: when awk
reaches end of file, there still 2 lines in buffer; printed.
the test:
$ cat text.txt 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 7 4 5 1 2 7 4 5 $ awk '$3=="7" && nr>2{b[3,1+nr%2]="0"} nr>2{i=1+nr%2;print b[1,i],b[2,i],b[3,i],b[4,i],b[5,i]} {i=1+nr%2;for(j=1;j<=nf;j++) b[j,i]=$j} end {for (i=1;i<=2;i++) print b[1,i],b[2,i],b[3,i],b[4,i],b[5,i]}' text.txt 1 2 3 4 5 1 2 0 4 5 1 2 0 4 5 1 2 7 4 5 1 2 7 4 5