awk 逐行循环遍历文件,并使用该值从包含该行值的 csv 文件中获取行

awk 逐行循环遍历文件,并使用该值从包含该行值的 csv 文件中获取行

我有 2 个文件,第一个:

值.txt

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

数据.csv

"username","email"
"user","[email protected]"
"user1","[email protected]"
"user2","[email protected]"
"user4","[email protected]"
"user456","[email protected]"
"user789","[email protected]"
"user5","[email protected]"
"user","[email protected]"
"user5","[email protected]"
"user","[email protected]"

我希望输出是这样的:

"user","[email protected]"
"user1","[email protected]"
"user2","[email protected]"
"user4","[email protected]"
"user5","[email protected]"
"user5","[email protected]"

我能做什么:

awk -F',' '$2 ~ /[email protected]/ {print $0}' data.csv > test1.csv

这将创建一个新文件 test1.csv,其中包含:

"user5","[email protected]"

无法弄清楚如何循环遍历文件并[email protected]与values.txt的行交换

答案1

awk -F, '
  NR==FNR{ a["\""$1"\""]; next }
  $2 in a
' values.txt data.csv

第一个输入文件:将每个字段保存在数组中a,并为每个键添加前缀/后缀"。继续记录next

第二个输入文件:测试 array 中是否存在第二个字段a。如果条件为真,则默认操作将打印记录。

相关内容