0

I need to print the loop index to a file using awk. Here is the code I used.

echo "Write the start and end file number:"
read sta end
echo "$sta" "$end"
for (( c="$sta"; c<="$end"; c++ ))
do
  echo "$c"
  awk '{if (NR < 15 && $8 >0.48 && $8 <0.52 && $9 >0.48 && $9 <0.52 && $10 >0.48 && $10 <0.52) {print $1 " " $8 " " $9 " " $10}}' RD00$c/MergerHalos.out >> center_raw.dat
done

In addiction to the 1,8,9,10th column values, I need to write the value of

c

to center_raw.dat.

3 Answers 3

3

I am not sure what your requirement is but from what i infer below seems to be what you require:

awk -v var="$c" '{if (NR < 15 && $8 >0.48 && $8 <0.52 && $9 >0.48 && $9 <0.52 && $10 >0.48 && $10 <0.52) {print var ":" $1 " " $8 " " $9 " " $10}}' RD00$c/MergerHalos.out >> center_raw.dat

-v option of awk is used to pass the external bash variable's value inside awk.

1
  • 2
    -v var="$c" passes value of $c to var. I have printed var in print var ":" $1 " " $8 " " $9 " " $10. You can use var wherever you want inside awk. I have used it in print just for an example.
    – Fazlin
    Oct 22, 2014 at 13:30
1

A quick rewrite stylistically (more DRY)

for (( c=sta; c<=end; c++ )); do
    awk -v c=$c '
        NR == 15 {exit}
        function ok(val) {return (0.48 < val && val < 0.52)}
        ok($8) && ok($9) && ok($10) {print c, $1, $8, $9, $10}
    ' RD00$c/MergerHalos.out
done >> center_raw.dat
1
  • From my experience using functions in awk massively affects performance
    – user78605
    Oct 22, 2014 at 14:10
0

You could do it all in awk i think

 awk '
 function readfile(i){
    file="RD00"i"/MergerHalos.out"
    while ( (getline < file) > 0) {
    if(NR < 15 && $8 >0.48 && $8 <0.52 && $9 >0.48 && $9 <0.52 && $10 >0.48 && $10 <0.52)
            print i":"$1,$8,$9,$10 > center_raw.dat
        }
        close(file)
}

BEGIN{
    sta=ARGV[1]
    end=ARGV[2]
    ARGC=0
    while(end>sta){print end;readfile(end--)}
}' $start $end

I think this may be overkill though

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .