Replace values in a file with values from another file

Hi,

I have 2 input files:

File 1:

echo Name > create_Name.txt 
echo Group /dir/group, Name >> create_Name.txt

File 2:

Name AAA BBB CCC
group A B C
dir A1 B1 C1

................................

Need to replace the contents of File 1 with column 2, 3 & 4 values of File 2 where ever column 1 of File 2 matches with the words in File 1. The number of output files would be number of columns in File 2 minus 1. In this case it would be 3.

ie., Contents of Output File1 (cre_AAA.sh) would be:

echo AAA > create_AAA.txt
echo Group /A1/A, AAA >> create_AAA.txt

Contents of Output File2 (cre_BBB.sh) would be:

echo BBB > create_BBB.txt
echo Group /B1/B, BBB >> create_BBB.txt

Contents of Output File3 (cre_CCC.sh) would be:

echo CCC > create_CCC.txt
echo Group /C1/C, CCC >> create_CCC.txt

and so on ...

File 1 is static but File 2 would be dynamic. There could be many columns (AAA, BBB,...FFF) and parameters (Name, dir, group, ... location) in it.

Can someone please help me with this?

Thanx

-Gc

Try something like this:

awk '
  NR==1{
    n=NF
  } 
  NR==FNR{
    for(j=2; j<=n; j++) A[$1,j-1]=$j
    W[$1]
    next
  } 
  {
    r=$0
    for(j=1; j<n; j++) {
      $0=r 
      for(i in W) gsub(i, A[i,j])
      print > ("create_" A["Name",j] ".txt")
    }
  }
' file2 file1

Thanks, Scrutinizer. But I am getting this error when running it:

awk: syntax error near line 6
awk: illegal statement near line 6
awk: syntax error near line 14
awk: illegal statement near line 14
awk: syntax error near line 15
awk: illegal statement near line 15

Hi, you would need to use the POSIX version of awk on Solaris: /usr/xpg4/bin/awk

Works beautifully well !... :b: Thanks, Scrutinizer.

How can I get all the new files created (create_*.txt) in a list?

You are welcome.. You could try changing the second part to this:

    r=$0
    for(j=1; j<n; j++) {
      $0=r 
      f="create_" A["Name",j] ".txt"
      if(FNR==1) print f
      for(i in W) gsub(i, A[i,j])
      print > f
    }

Thanks, almost there ... it lists the files on screen. I need them saved to a file, so that they can be executed as a script.

Something like:

ls create_*.txt > create_master.txt

Yes so when calling the script, you can redirect the script's "screen" output to a file using standard UNIX redirection.

Figured it out, added a redirect at the end and it works just fine now!.

Thanks once again Scrutinizer, appreciate the prompt responses.