比较.txt和.csv文件,需要将.csv文件中的匹配名称替换为.txt [英] Compare a .txt and .csv file and need to replace with matching name in .csv file to .txt
问题描述
file1.txt
file1.txt
[fields:WinSpc:defect]
a=b
b=c
hello=hi
[fields:ROCKET PROJECT:ticket]
description=Descrtiption
status=status
[fields:PROJECT_Nexus:defect]
title=summary
priority=Priority_hello
file2.csv
file2.csv
WinSpc,projects.winspc
ROCKET PROJECT,projects.rocket_project
PROJECT_Nexus,projects.project-nexus
我需要匹配这两个文件,所需的输出将是:
I need to match these two files and desired output would be :
output.txt
output.txt
[fields:winspc:defect]
a=b
b=c
hello=hi
[fields:rocket_project:ticket]
description=Descrtiption
status=status
[fields:project-nexus:defect]
title=summary
priority=Priority_hello
只需更改名称,
我已尝试使用
grep -Fwf, diff --breif,
和awk选项,但无法获得所需的输出。仍在学习这些东西。任何建议将是非常有益的。提前感谢。
and awk options but not getting desired output. Still learning these things. Any suggestions would be very helpful. Thanks in advance.
推荐答案
可以进行更具扩展性的 Awk
逻辑
A more scalable Awk
logic can be done something as below.
重新确认未来读者的要求,
.csv
文件具有存储在多行中的字段,替换字段
1 。对于中的所有
字段
,.txt
文件应替换为替换字段
Re-affirming the requirement for future readers, the
.csv
file has afield,replacement-of-field
1 pair stored in multiple lines. For all thosefield
in.csv
the corresponding entries in.txt
file should be replaced withreplacement-of-field
1. replcement-of-field 实际上只涉及
以下命令按预期执行作业。
The below command does the job as intended.
awk 'FNR==NR{split($2,list,"."); replacement[$1]=list[2]; next} \
{for (i in replacement){ if (match($0,i)) {gsub(i,replacement[i],$0); break} }}1 ' \
FS="," file2.csv file1.txt
产生 OP
所需的输出,
[fields:winspc:defect]
a=b
b=c
hello=hi
[fields:rocket_project:ticket]
description=Descrtiption
status=status
[fields:project-nexus:defect]
title=summary
priority=Priority_hello
投入一点解释,
-
FNR == NR
逻辑确保在.csv
文件中首先运行{}
之后的命令。请注意,使用字段分隔符,
- 读取
.csv
code> split($ 2,list,。); replacement [$ 1] = list [2]; next 确保文件的第二列被分割。
,创建一个哈希映射,索引设置为要替换的值,值作为要替换的实际值。对.csv
文件中的所有行执行此操作 - 现在在
.txt
文件,检查每行是否存在要替换的值,如果存在,则替换为替换值。
FNR==NR
logic ensures the command after it within{}
is run first for the.csv
file. Note that.csv
file is read with field-separator,
split($2,list,".");replacement[$1]=list[2]; next
ensures that the second column of the file is split by.
and a hash-map is created with index set to value to be replaced and the value as actual value to be replaced. This is done for all the lines in the.csv
file- Now on the
.txt
file, for each line is checked to see if the value to be replaced is present, if present it is replaced with the replacement value.
这篇关于比较.txt和.csv文件,需要将.csv文件中的匹配名称替换为.txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!