【问题标题】:How to use awk to search for a complete match of text within one column of a CSV file and to only output the first matching line?如何使用 awk 在 CSV 文件的一列中搜索完全匹配的文本并仅输出第一个匹配行?
【发布时间】:2012-04-18 09:20:03
【问题描述】:

我正在使用来自How to restrict grep to search only the one column within a CSV file, but to output matching lines in their entirety? 的答案用 awk 搜索特定列,然后输出匹配的行,例如:

awk -F@ "{if (\$2 ~ /$find_me/ ) { print \$0; } }" <input_file>
  • 如何将搜索限制为仅匹配列与 $find_me 完全匹配的行?
  • 如何将搜索限制为仅输出文件中找到的第一个匹配项?

【问题讨论】:

    标签: csv awk


    【解决方案1】:

    你可以试试这个:

    awk -F@ -v pattern="$find_me" '$2 ~ "^" pattern "$"' input.txt
    

    或者

    awk -F@ -v pattern="^$find_me\$" '$2 ~ pattern' input.txt
    

    【讨论】:

    • 当我用一些文本替换 $fine_me 时它可以工作,但当使用 $fine_me 时它不会工作。
    • @Village:确保您使用了正确的引号,如kev的答案所示。此外,要仅打印第一个匹配项,请使用 awk -F@ -v pattern="$find_me" '$2 ~ "^" pattern "$" {print; exit}' input.txt
    猜你喜欢
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2015-07-06
    相关资源
    最近更新 更多