[英]If the first column of file1 matches any string in file2, then replace it with the second column of file1
[英]TCL script search string from file1 & file 2 and replace it in file1
我有 2 个文件。 我想从文件 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 中最后一个“/”和“_place_INT”之间的内容。例如:文件 1 中的搜索内容将是:
a_xyz123
b_pqr987
现在脚本应该在文件 2 中查找此搜索内容搜索整个字符串并替换文件 1 中的此搜索内容:例如:脚本将在文件 2 中搜索“a_xyz123”,因此它将获得此字符串 'Par/pgh/fgf/ a_xyz123 _inst '。 现在脚本应该在 file1 中替换它。
预期 output 文件 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”,因为它们都有 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
例子:
$ 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'
尝试这个
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.