Nishant Nishant - 1 year ago 54
Bash Question

I need help on script which will find particular value from one file and replace it in another file

I have two data files, ABC and XYZ:

Partial contents of ABC:

cancsi(64): 10-s01: (c) Copyright 1995-2014
cancsi> source ncancsi
cancsi> set dump_shm on

*Ve3* Loading
*Ve3* : Parallel Dumping.

// X_deb: step # : 9
// X_deb: in : 4'b0000
// X_deb: out : 4'b1110
// X_deb: load (4 , 4'b1010) ;
// X_deb: MK : 4'b1111

// X_deb: step # : 10
// X_deb: in : 4'b0100
// X_deb: out : 4'b1001
// X_deb: load (4 , 4'b1100) ;

// X_deb: step # : 11
// X_deb: in : 4'b0001
// X_deb: out : 4'b1100
// X_deb: load (4 , 4'b1011) ;
// X_deb: MK : 4'b1110

Contents of file XYZ:

This is output file..
Run 5
"Random text"
X_step_9 4 4'b1010 ( 4'b1110)
X_step_10 4 4'b1100 (4'b1001)
X_step_11 4'b1011 (4'b1100)

Format syntax of file XYZ:

X_step_# (if MK is present for the step, then MK value for the step, otherwise extract value for that step from ABC file. ).

The script I was using was having some issues, it was unable to grep an MK value for the step and put it in XYZ file, instead of that the script was putting "out" value for all the steps.
Unfortunately I deleted that script.
NOTE: in ABC file, not all steps have an MK value. (In the above example only step 9 and 11 have an MK value).

Now I need to create one generic script (in any language) for all the steps (there are many steps, not only 9,10,11) which can do the following things:

  • it will
    MK value for particular step from ABC file.

  • after that it will
    for that step in XYZ file (X_step_#) and replace "out" value with MK value.
    For example: Script will find MK value for step 9 from ABC and then it will search for X_step_9 in XYZ file and replace "out" value with MK value.

Someone please help me on this.

Answer Source

(Tcl solution) You might try something like this, if I understand your specification correctly:

proc // args {
    global step data
    set args [lassign $args _ kword]
    set val [lindex $args end]
    switch -- $kword {
        step {
            set step $val 
        MK {
            dict set data $step MK $val

proc make_XYZ {in out data} {
    while {[gets $in line] >= 0} {
        if {[regexp {^\s*X_step_(\d+)} $line -> n] && [dict exists $data $n MK]} {
            regsub {\(.*\)} $line ([dict get $data $n MK]) line
        puts $out $line

rename unknown _unknown
proc unknown args {}
set data {}
source ABC
rename unknown {}
rename _unknown unknown
file rename -force XYZ XYZ.bak
set f1 [open XYZ.bak r]
set f2 [open XYZ w]
make_XYZ $f1 $f2 $data
close $f1
close $f2

Documentation: && (operator), close, dict, file, gets, global, if, lassign, lindex, open, proc, puts, regexp, regsub, rename, set, source, switch, unknown, while