简体   繁体   English

awk查找并在匹配时将变量file2替换为file1

[英]awk find and replace variable file2 into file1 when matched

Tried couple of answers from similar questions but not quite getting correct results. 尝试了类似问题的答案,但并没有获得正确的结果。 Trying to search second file for variable and replace with second variable if there, otherwise keep original... 尝试在第二个文件中搜索变量,如果有则替换为第二个变量,否则保留原始文件...

File1.txt File1.txt

a
2
c
4
e
f

File2.txt File2.txt

2 b
4 d

Wanted Output.txt 想要的Output.txt

a
b
c
d
e
f

So far what I have seems to sort of work, but anywhere the replacement is happening I'm getting a blank row instead of the new variable... Current Output.txt 到目前为止,我似乎可以进行一些工作,但是在发生替换的任何地方,我都会得到空白行而不是新变量... Current Output.txt

a

c

e
f

Curent code.... 当前代码...

awk -F'\t' 'NR==FNR{a[$1]=$2;next} {print (($1 in a) ? a[$1] : $1)}' file2.txt file1.txt > output.txt

Also tried and got same results... 也尝试过并得到相同的结果...

awk -F'\t' 'NR==FNR{a[$1]=$2;next} {$1 = a[$1]}1' file2.txt file1.txt > output.txt 

Sorry first wrote incorrectly..fixed the key value issue. 对不起,首先写错了。.解决了键值问题。

Did try what you did, still not getting missing in output.txt 尝试过您所做的事情,但仍然不会在output.txt中丢失

awk -F'\t' 'NR==FNR{a[$1]=$2;next} $1 in a{$1 = a[$1]}1' file2.txt file1.txt > output.txt

your key value pair is not right... $1 is the key, $2 is the value. 您的键值对不正确... $ 1是键,$ 2是值。

$ awk -F'\t' 'NR==FNR{a[$1]=$2;next} $1 in a{$1=a[$1]}1' file.2 file.1
a
b
c
d
e
f

try below solution - 尝试以下解决方案-

awk 'NR==FNR{a[$1]=$NF;next} {print (a[$NF]?a[$NF]:$1)}' file2.txt file1.txt

a
b
c
d
e
f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 sed 或 awk 将 file1 的一部分替换为 file2 的一部分,部分由行和列描述 - How to replace a portion of file1 by a portion of file2 uing sed or awk, portion delineated by row and column no 在awk中将文件1的一个字段与文件2的另一个字段进行比较 - Comparing one field of file1 to other field of file2 in awk sed用file1中的file3内容替换file2内容 - sed replace file2 content with file3 content in file1 如果在文件 2 中找不到字符串,则用空格替换文件 1 中的字符串 - replace strings in file1 with empty space if strings not found in file2 在基于file1的file2中搜索字符串并替换 - Search for a string in file2 based on file1 and replace bash-根据file2中的ID查找file1中的名称 - bash - Find names in file1 according to IDs in file2 从文件 2 中的文件 1 中找到最近的点,shell 脚本 - Find nearest point from file1 in file2, shell skript 如果file1的第一列与file2中的任何字符串匹配,则将其替换为file1的第二列 - If the first column of file1 matches any string in file2, then replace it with the second column of file1 需要用file1的第二列替换与file1的第一列匹配的file2中的字符串 - Need to replace string in file2 that matches first column of file1 with second column of file1 当file1包含额外信息时,使用file1作为索引来搜索file2 - Using file1 as an Index to search file2 when file1 contains extra informations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM