TCL脚本搜索file1和file2中的字符串,并在file1中替换它

2024-06-28 11:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件。我想从文件2中查找特定内容,并替换文件1中该内容匹配的完整实例字符串

文件1的部分内容:

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

文件2的部分内容:

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

--

在这里,脚本应该开始搜索文件1中最后一个“/”和“\u place\u INT”之间的内容。例如: 从文件1中搜索的内容将是:

a_xyz123 
b_pqr987

现在,脚本应该在文件2中查找此搜索内容搜索整个字符串,并替换文件1中的此搜索内容: 例如:脚本将在文件2中搜索“a_xyz123”,因此它将得到这个字符串“Par/pgh/fgf/a_xyz123\u inst”。 现在,脚本应该在文件1中替换这个

预期输出文件1:

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

在这里,您可以看到Par/abc/a_xyz123_place_INT被替换为'Par/pgh/fgf/a_xyz123_inst',因为这两者都有一个_xyz123


Tags: 文件字符串脚本内容placeallintabc
2条回答

试试这个

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

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

例如:

$ 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'

相关问题 更多 >