Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

GAWK: Replacing a variable in an output file

Status
Not open for further replies.

Shau

Technical User
Mar 30, 2005
1
SI
Hi, I have an input file (input.txt): ====== # The four columns represent Name, Country, Age and City respectively.

(Row 1) John China 28 Beijing
(Row 2) Matt USA 40 San-Francisco
(Row 3) Cathy Englan 50 London
.. .. ..
.. .. ..
======
I have a Master template file (Master.txt):

$Name is from $Country. $Name is $Age years old, and comes from $City.

======

For each row (person) in the input file, I would like a new output to be produced with the filename $Name.txt, which is based on the Master.txt template.

Can someone show how this is easily done. (I was told that gawk/awk (or sed) could do it easily, but I am not very familiar with them yet, and I did not find a similar example in the User Guide for GAWK.) Thanks.

 
nawk shau.awk Master.txt input.txt

here's shau.awk:
Code:
BEGIN {
   colN=split("Name Country Age City", colA, " ")
   for(i=1; i <= colN; i++)
      if ( i != colA[i] ) {
         colA[colA[i]] = i
         delete colA[i]
      }
}

FNR == NR {
  tmpl=$0
  next
}
{
  tmpT=tmpl
  for(i in colA)
    gsub("\\$" i, $colA[i], tmpT)

  print tmpT
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
I assumed there's no '(Row #)' in the REAL input.txt

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
here's a bit better version supporting multiple lines in the Master.txt file.

Code:
BEGIN {
   colN=split("Name Country Age City", colA, " ")
   for(i=1; i <= colN; i++)
      if ( i != colA[i] ) {
         colA[colA[i]] = i
         delete colA[i]
      }
}

FNR == NR {
  tmpl[FNR]=$0
  tmplLines++
  next
}
{
  for (tmplIter=1; tmplIter <= tmplLines; tmplIter++) {
     tmpT=tmpl[tmplIter]
     for(i in colA)
       gsub("\\$" i, $colA[i], tmpT)

     print tmpT
  }
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Here try this:

awk '{print $1 "is from " $2 ". " $1 "is " $3 "years old, and comes from " $4 "."}' Master.txt

Frank
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top