bash - AWK 寻找一种方法来打印包含逗号分隔字符串中的单词的行

标签 bash awk scripting matching

我想编写一个 bash 脚本,它只打印在第二列中包含逗号分隔字符串中的单词的行。示例:

words="abc;def;ghi;jkl"

>cat log1.txt
hello;abc;1234
house;ab;987
mouse;abcdef;654

我想要的是仅打印包含“words”变量中的整个单词的行。这意味着“ab”不匹配,“abcdef”也不匹配。这看起来很简单,但在尝试了很多小时后,我还是找不到解决方案。

例如,我尝试将此作为我的 awk 命令,但它匹配任何子字符串。

-F \; -v b="TSLA;NVDA" 'b ~ $2 { print $0 }'

我将不胜感激任何帮助。谢谢。

编辑:

示例输入如下所示

1;UNH;buy;344.74
2;PG;sell;138.60
3;MSFT;sell;237.64
4;TSLA;sell;707.03

会设置这样的变量

filter="PG;TSLA"

根据这个过滤器,我想回应这些行

2;PG;sell;138.60
4;TSLA;sell;707.03

最佳答案

Grep 是一个不错的选择:

grep -Fw -f <(tr ';' '\n' <<<"$words") log1.txt

我会用 awk

awk -F ';' -v w="$words" '
    BEGIN {
        n = split(w, a, /;/)
        # next line moves the words into the _index_ of an array, 
        # to make the file processing much easier and more efficient
        for (i=1; i<=n; i++) words[a[i]]=1
    }
    $2 in words
' log1.txt

关于bash - AWK 寻找一种方法来打印包含逗号分隔字符串中的单词的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66733696/

相关文章:

powershell - 尝试使用 powershell 将数组导出到 csv(数组对象是 ; 分隔并包含换行符)

linux - awk从列中找到最大值和最小值并存储在其他列中

Bash 中的正则表达式 : not wanting to include directories

linux - 如何在 Bash 脚本中回答是

python - Bash 到 Python : flatten directory tree

bash - 在 makefile 中运行服务器和客户端

bash - 如何比较两条相对于空间相反的线

python - 从 sql 脚本中提取模式

linux - 使用 tac 和 sed 反转文件

bash - 您可以使用 sed 将日期转换为 yyyy/mm/dd 吗?