【问题标题】:AWK Finding a way to print lines containing a word from a comma separated stringAWK 找到一种方法来打印包含逗号分隔字符串中的单词的行
【发布时间】:2021-06-18 08:50:57
【问题描述】:

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

【问题讨论】:

  • "abc;def;ghi;jkl" 是分号分隔的字符串,不是逗号分隔的。

标签: bash awk scripting matching


【解决方案1】:

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 grep -Fwf- &lt;&lt;&lt;"${words//;/$'\n'}" file
  • 该 grep 命令会在它出现在一行中的任何位置找到单词,而不仅仅是在第二个字段中,并且如果任何字段包含非单词组成字符,则会产生部分匹配。
  • 那个 awk BEGIN 语句可以是split(w, a); for (i in a) words[a[i]]
【解决方案2】:

你可以使用这个awk:

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

hello;abc;1234

【讨论】:

  • 感谢您的回答。你能解释一下index(s, FS $i FS)的含义吗? FS 由 -F ';' 自动设置是';',但是那个索引命令不是暗示两边都应该有分隔符吗?
  • 当我们使用-F';' 时,我们会用; 分割每个字段。然后在index 函数中,我们在每个字段的两边都用; 包装,即FS $i FS。我们的变量s 已经有; 作为分隔符和在开始/结束。这使我们能够调用 index 函数来进行完全匹配。
猜你喜欢
  • 2013-01-08
  • 2013-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
相关资源
最近更新 更多