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