[英]TCL script search string from file1 & file 2 and replace it in file1
I have 2 files.我有 2 个文件。 I want to find specific content from file 2 and replace the complete instance string in the file 1 where that content matches.我想从文件 2 中查找特定内容并替换文件 1 中该内容匹配的完整实例字符串。
Partial Content of file 1:文件1的部分内容:
// ALL xyz vev1 Par/abc/a_xyz123_place_INT
// ALL ieug vev2 Par/abc/b_pqr987_place_INT
Partial Content of file 2:文件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:在这里,脚本应该开始搜索文件 1 中最后一个“/”和“_place_INT”之间的内容。例如:文件 1 中的搜索内容将是:
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'.现在脚本应该在文件 2 中查找此搜索内容搜索整个字符串并替换文件 1 中的此搜索内容:例如:脚本将在文件 2 中搜索“a_xyz123”,因此它将获得此字符串 'Par/pgh/fgf/ a_xyz123 _inst '。 Now script should replace this in file1.现在脚本应该在 file1 中替换它。
Expected output file1:预期 output 文件 1:
// 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.在这里,您可以看到 Par/abc/a_xyz123_place_INT 被替换为“Par/pgh/fgf/a_xyz123_inst”,因为它们都有 a_xyz123。
tcl: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.