avvk
December 21, 2008, 7:22pm
1
It can't be that hard, but I just can't figure it out:
I have file like:
File Sub-brick M_1 S_1 M_2 S_2 M_4 S_4 ...
xxx 1 214 731 228 621 132 578 ...
and would like to get 0 0 where M_3 S_3 is missing
xxx 1 214 731 228 621 0 0 132 578 ...
I wrote following script, but can't figure out how to print from second line
awk -F " " -v j=0 'NR==1 {for (i=3; i<=NF; i=i+2) { j=j+1; h=i+1; k="Mean_"j; if ($i != k) { printf "%s %s ",0, 0; i=i-2 } else printf "%s %s ", $i, $h} printf "\n" }' file
and output is:
M_1 S_1 M_2 S_2 0 0 M_4 S_4 ...
Any ideas?
thanks in advance
Hi,
if you file consists of lines like:
File Sub-brick M_1 S_1 M_2 S_2 M_4 S_4 ...
xxx 1 214 731 228 621 132 578 ...
File Sub-brick M_1 S_1 M_2 S_2 M_4 S_4 ...
xxx 1 214 731 228 621 132 578 ...
output will be:
xxx 1 214 731 228 621 0 0 132 578 ...
xxx 1 214 731 228 621 0 0 132 578 ...
With:
awk '($1 ~ /^File/) && !($0 ~ /M_3 S_3/){\
getline;b=$0;\
gsub(/(\w+ [0-9]+ [0-9]+ [0-9]+ [0-9]+ [0-9]+)/,"& 0 0",b);\
print b;}' file1
HTH Chris
avvk
December 22, 2008, 7:32am
3
I didn't specify it good.
Any column pair can be missing (from 1 to (NF-2)/2) so that's why I have loop : for (i=3; i<=NF; i=i+2)
and then j=j+1, as counter
In above example you can see missing M_3 S_3
I read somewhere that you can reset NR any time, but if I put NR=2 before print nothing happens.
And in file is just header line, and the second line
Why to make script?, because I have a lot of files.
Thanks
avvk
December 22, 2008, 10:28am
4
Have found the way
BEGIN {FS=OFS=" "}
{
for (i=1;i<=NF;i++)
{
arr[NR,i]=$i;
}
}
END {
h=0
for(j=3;j<=NF;j=j+2)
{
h=h+1;
k="M_"h;
if (arr[1,j] != k)
{
printf("%s %s ",0,0);
j=j-2;
}
else if (arr[1,j] == k)
{
printf("%s %s ",arr[2,j],arr[2,j+1]);
}
}
printf("\n");
}