简体   繁体   English

包含在文件中的grep正则表达式(不是grep -f选项!)

[英]Grep regex contained in a file (not grep -f option!)

I am reading some equipment configuration output and check if the configuration is correct, according to the HW configuration. 我正在阅读一些设备配置输出,并根据硬件配置检查配置是否正确。 The template configurations are stored as files with all the params, and the lines contain regular expressions (basically just to account for variable number of spaces between "object", "param" and "value" in the output, also some index variance) 模板配置存储为包含所有参数的文件,并且这些行包含正则表达式(基本上只是为了考虑输出中“object”,“param”和“value”之间的可变空格数,还有一些索引方差)

First of all, I cannot use grep -f $template $output , since I have to process each line of the template separately. 首先,我不能使用grep -f $template $output ,因为我必须分别处理模板的每一行。 I have something like this running 我有类似的东西在运行

while read line
  do
  attempt=`grep -E "$line" $file`
  # ...etc
  done < $template

Which works just fine if the template doesn't contain regex. 如果模板不包含正则表达式,哪个工作正常。 Problem: grep interpretes the search option literally when these are read form file. 问题:当这些是读取表单文件时,grep会逐字地解释搜索选项。 I tested the regex themselves, they work fine from the command line. 我自己测试了正则表达式,它们在命令行中运行良好。

With this background, the question is: 在此背景下,问题是:

How to read regex from a file (line by line) and have grep not interprete them literally? 如何从文件中读取正则表达式(逐行)并让grep不按字面解释它们?

Use the -F option, or fgrep . 使用-F选项或fgrep

What's more, you seem to want to match full lines: add the -x option as well. 更重要的是,您似乎想要匹配整行:添加-x选项。

Using the following script: 使用以下脚本:

#!/usr/bin/env bash
# multi-grep
regexes="$1"
file="$2"
while IFS= read -r rx ; do
    result="$(grep -E "$rx" "$file")"
    grep -q -E "$rx" "$file" && printf 'Look ma, a match: %s!\n' "$result"
done < "$regexes"

And files with the following contents: 以及包含以下内容的文件:

$ cat regexes
RbsLocalCell=S.C1.+eulMaxOwnUuLoad.+100

$ cat data
RbsLocalCell=S1C1 eulMaxOwnUuLoad 100

I get this result: 我得到这个结果:

$ ./multi-grep regexes data
Look ma, a match: RbsLocalCell=S1C1 eulMaxOwnUuLoad 100!

This works for different spacing as well 这适用于不同的间距

$ cat data
RbsLocalCell=S1C1    eulMaxOwnUuLoad           100

$ ./multi-grep regexes data
Look ma, a match: RbsLocalCell=S1C1    eulMaxOwnUuLoad           100!

Seems okay to me. 好像对我来说。

Another point: make sure the pattern is not interpreted in some wrong way by the shell by putting "$line" in quotes. 另一点:通过在引号中加入"$line" ,确保shell不会以某种错误的方式解释模式。

All in all that looks like you better write a perl than a shell script. 总而言之,你最好写一个perl而不是shell脚本。

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

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