简体   繁体   中英

TCL script search string from file1 & file 2 and replace it in file1

I have 2 files. I want to find specific content from file 2 and replace the complete instance string in the file 1 where that content matches.

Partial Content of file 1:

// ALL xyz   vev1      Par/abc/a_xyz123_place_INT
// ALL ieug  vev2      Par/abc/b_pqr987_place_INT

Partial Content of file 2:

// Vev Inst: 'Par/pgh/fgf/a_xyz123_inst'
// Vev Inst: 'Par/pgh/sgg/gdgg/b_pqr987_inst'

--

Here, script should start search for the content between last "/" and "_place_INT" from file 1. For ex: Searched content from file 1 will be:

a_xyz123 
b_pqr987

Now script should look for this search contents in file 2 search entire string and replace this searched content in file 1: For ex: script will search "a_xyz123" in file 2 so it will get this string 'Par/pgh/fgf/ a_xyz123 _inst'. Now script should replace this in file1.

Expected output file1:

// ALL xyz   vev1    'Par/pgh/fgf/a_xyz123_inst'
// ALL ieug  vev2    'Par/pgh/sgg/gdgg/b_pqr987_inst'

Here you can see Par/abc/a_xyz123_place_INT is replaced with 'Par/pgh/fgf/a_xyz123_inst' as both of these has a_xyz123.

tcl:

#!/usr/bin/env tclsh

proc main {file1 file2} {
    set f2 [open $file2 r]
    set f2contents [read $f2]
    close $f2

    set f1 [open $file1 r]
    while {[gets $f1 line] > 0} {
        if {[regexp {([^/]+)_place_INT$} $line _ pat]} {
            set re [string cat {'[\w/]+} $pat {\w+'}]
            if {[regexp $re $f2contents replacement]} {
                regsub {[\w/]+$} $line $replacement line
            }
        }
        puts $line
    }
    close $f1
}

main {*}$argv

Example:

$ tclsh demo.tcl file1.txt file2.txt
// ALL xyz   vev1      'Par/pgh/fgf/a_xyz123_inst'
// ALL ieug  vev2      'Par/pgh/sgg/gdgg/b_pqr987_inst'

try this

while read line; 
do 
search_str=$(echo ${line}| sed 's#.*\/##g;s#_place_INT##');
replace_str=$(grep -o "'.*${search_str}.*'" file2.txt);
if test -z "$replace_str" 
then 
    echo ${line} >> file1.txt.tmp; 
else 
    echo ${line} | awk -v str="${replace_str}" '{$NF=str; print }' >> file1.txt.tmp; 
fi
done < file1.txt
mv file1.txt.tmp  file1.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM