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

问题描述

我想编写一个 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
,

您可以使用此awk

words="abc;def;ghi;jkl"
awk -F';' -v s=";$words;" 'index(s,FS $2 FS)' log1.txt

hello;abc;1234