AWK manipulation in bash script

EDIT: This has been SOLVED. Thanks!

Greetings everyone,

I've posted a few threads with some quick help questions, and this is another one of those. I can't post enough gratitude for those much more knowledgeable than myself who are willing to give good advice for my minor issues. Now, onto my problem!

I have a file that contains a single column of random numbers called 'random.dat' for eases' sake, let's say it contains only one number. My goal is to write a bash script that looks at these numbers, scans through another file (in this case, tmp2.dat), and prints some of the original values, and some modified values. Let me show you the line I have, then explain the issue I come up with;

for num in `cat random.dat`
do
#  echo "$num"
  awk -v num=$num '{if (FNR==num) print $1,$2,"1","2",$5,$6,$7,$8,$9,$10;
  else print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10}' tmp2.dat >> tmp3.dat
done

So, the script should look at the random number in random.dat, search through the file for the correct row, then print the modified column which includes '1' and '2' instead of whatever $3 and $4 are. Note that I want it to keep all of the rows that aren't in the random number file the same. The problem is that if there are more than one random number in the random.dat file, it only changes the last row of the file that matches the random number, leaving all of the others unchanged.

To summarize, I would like my script to turn this file:

1.0  1  6  12 0.0 0.0 0.0 1.0 2.0 3.0
1.0  1  6  12 1.0 0.0 0.0 1.0 2.0 3.0
1.0  1  6  12 2.0 0.0 0.0 1.0 2.0 3.0 

Into this (assume random.dat contained the number '2')
(bolded parts are what should be changed for the row, indicated in the awk portion of the script)

1.0  1  6  12 0.0 0.0 0.0 1.0 2.0 3.0
1.0  1  1   2 1.0 0.0 0.0 1.0 2.0 3.0
1.0  1  6  12 2.0 0.0 0.0 1.0 2.0 3.0 

I hope I explained things as well as possible, please let me know if you have any questions. Thanks again for anyone who is willing to help me solve this dilemma!

Best regards,
Eblue

Like this?

awk 'NR==FNR{r[$1]=1;next}r[FNR]==1{$3=1; $4=2}1' rand.dat temp.dat
  • read rand.dat and store the contents into an associative array 'r'
  • for each line of temp.dat, if r[FNR]==1, then change $3 and $4.
  • Print every line (the '1' and the end)

mirni,

Thanks so much for your response! I tested the script out and it seems to do what I wanted it to do. I'm currently testing one last thing, and I will edit this post to let you know if it worked. It's looking good though, and I'm keeping my finger's crossed.

Thanks again!

EDIT: Everything works wonderfully, thanks for your help!