gpt4 book ai didi

linux - awk: $2 ==/"foo"/{ ... } 没有按预期工作(将 $2 与 foo 完全匹配,引用)

转载 作者:太空狗 更新时间:2023-10-29 11:49:35 26 4
gpt4 key购买 nike

以这个文件为例:

"line1_value1","foo","line1_value3"
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
"line4_value1","foo","line4_value3"
"line3_value1","faa ","line3_value3"

我希望在第二列中获取第二列完全等于“faa”的所有行。在我的示例中,这与第 2 行和第 3 行匹配。我试过了:

awk -F, '$2 == /"foo"/ { print $0 }' example_file

但是这个命令什么都不返回...我哪里错了?

最佳答案

, 进行相等性测试分隔的第二个字段:

awk -F, '$2 == "\"faa\""' file.txt

同样在这里,你需要转义内部" s 让它在里面变成字面意思 "

示例:

% cat file.txt                      
"line1_value1","foo","line1_value3"
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
"line4_value1","foo","line4_value3"
"line3_value1","faa ","line3_value3"

% awk -F, '$2 == "\"faa\""' file.txt
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"

失败的原因:

您使用过:

awk -F, '$2 == /"foo"/ { print $0 }'
  • //awk 中引发正则表达式匹配,并返回 0 (不匹配)或 1 (匹配)

  • $2 == /"foo"/必须比较(为了相等)第二个字段与整数 01 ,在这种情况下将始终评估为 false。另外,/"foo"/这里匹配模式 "foo"反对整个记录

  • 所以,请记住,/<pattern>/$0 ~ /<pattern>/ 的简写因此你的$2 == /"foo"/$2 == ($0 ~ /"foo"/) 的简写

关于linux - awk: $2 ==/"foo"/{ ... } 没有按预期工作(将 $2 与 foo 完全匹配,引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44996796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com