AWK 寻找一种方法来打印包含逗号分隔字符串中的单词的行
AWK Finding a way to print lines containing a word from a comma separated string
我想编写一个 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 ~ { print [=11=] }'
如有任何帮助,我将不胜感激。谢谢。
编辑:
示例输入如下所示
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
你可以使用这个awk
:
words="abc;def;ghi;jkl"
awk -F';' -v s=";$words;" 'index(s, FS FS)' log1.txt
hello;abc;1234
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
}
in words
' log1.txt
我想编写一个 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 ~ { print [=11=] }'
如有任何帮助,我将不胜感激。谢谢。
编辑:
示例输入如下所示
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
你可以使用这个awk
:
words="abc;def;ghi;jkl"
awk -F';' -v s=";$words;" 'index(s, FS FS)' log1.txt
hello;abc;1234
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
}
in words
' log1.txt