Multiple Replacement in a Text File in one operation (sed/awk) ?

Hi all,

Saying we have two files:

  1. A "Reference File" whose content is "Variable Name": "Variable Value"

  2. A "Model File" whose content is a model program in which I want to substitute "VariableName" with their respective value to produce a third file "Program File" which would be a program tailored for my need !

[x004191a@xsnl11p317a TEST_DAE]$ cat Reference
@TargetTable:TT
@CurrentDate:2016-08-02
@TargetDb:CDH_DEV
[x004191a@xsnl11p317a TEST_DAE]$ cat Model_File
/*
===============================================
   NOM Script  : @TargetTable.tpt
   TYPE        : Script TPT
   DESCRIPTION : DOMAINE METADATA - CHARGEMENT -
   AUTEUR      : DAE
   DATE        : @CurrentDate
===============================================   HISTORIQUE

   DATE        AUTEUR  CREATION/MODIFICATION
   08/01/2016  DAE     CREATION
===========================================================================
*/

USING CHARACTER SET UTF-8
DEFINE JOB TPT_@TargetTable
DESCRIPTION 'CHARGEMENT @TargetTable'

The aim is to produce that third file without using multiple sed substitution operations:

[x004191a@xsnl11p317a TEST_DAE]$ cat Program_File
/*
===========================================================================
   NOM Script  : TT.tpt
   TYPE        : Script TPT
   DESCRIPTION : DOMAINE METADATA - CHARGEMENT -
   AUTEUR      : DAE
   DATE        : 2016-08-02
===========================================================================
*/

USING CHARACTER SET UTF-8
DEFINE JOB TPT_TT
DESCRIPTION 'CHARGEMENT TT'

[x004191a@xsnl11p317a TEST_DAE]$

Any kind of help would be greatly appreciated,

Didier.

Try something like:

awk -F: 'NR==FNR{A[$1]=$2; next} {for(i in A) gsub(i, A)}1' Reference Modelfile 
1 Like

Excellent Scrutinizer !!! :slight_smile:

Thanks a lot,

Didier.

Next step: understand how it is running, not obvious to me ! :slight_smile:

awk -F: '                        # Set the input field separator to ":"
  NR==FNR{                       # When the first file is being read (only then are FNR and NR equal) 
    A[$1]=$2                     # create an (associative) element in array A with the first field as the index and the 2nd field as value (this contains the replacements)
    next                         # start reading the next record (line)
  } 
  {                              # while reading the second file, for every line (record)
    for(i in A) gsub(i, A)    # for every replacement that was read from the first file, replace every occurrence on the line
  }
  1                              # print the record (line)
' Reference Modelfile            # read file 1 and then file 2
1 Like

Thanks a lot for your detailed explanation, Scrutinizer: I would never be able to find that by myself !