繁体   English   中英

从文件动态创建模式列表以在 grep -f 中运行

[英]Create pattern list dynamically from file for running in grep -f

可以说我有这个输入

11
12
31
40
42
90

我需要从文件中获取所有数字行并添加| 每个字符后面的字符都可以用作与grep -f一起运行的模式列表。

我正在考虑使用xargs但我不知道如何使用| 作为分隔符或将 args 放在字符串的中间

grep -P "(11|12|31|40|42|90)\|" o.txt

您可以使用

grep -E -f <(sed -E '/^[0-9]+$/!d;s/.*/&\\|/' numbers.txt) file.txt

首先,从numbers.txt中获取所有仅包含数字的行,append 到每个找到的行 a \| ,然后将其用作带有-f选项的模式文件grep file.txt是您要查找匹配项的文件。

查看在线演示

#!/bin/bash
text='Some 11 number and 11| that we need
Redundant line'
s="11
12
31
40
42
90"
grep -E -f <(sed -E '/^[0-9]+$/!d;s/.*/&\\|/' <<< "$s") <<< "$text"
# => Some 11 number and 11| that we need
grep -oE -f <(sed -E '/^[0-9]+$/!d;s/.*/&\\|/' <<< "$s") <<< "$text"
# => 11|

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM