【问题标题】:How to search for multiple Substrings in a string如何在一个字符串中搜索多个子字符串
【发布时间】:2020-06-25 07:53:00
【问题描述】:

我是 bash 编程的新手,我一直在尝试编写一个函数来搜索字符串中的多个子字符串以进行日志分析。

例如: 我有一个日志文件,其中包含这样的字符串:

“01-01-2020 STREETNEW 函数触发命令 3 已处理 - 已创建新街道。”

现在我想在这个字符串中搜索 2 个子字符串。 我要查找的第一个子字符串是“Command 3”,用于识别触发了哪个操作。如果找到“Command 3”,我想搜索第二个子字符串“New street created”来检查触发操作的输出。

到目前为止,我编写了一个包含函数,它可以帮助我找到匹配项,并且到目前为止效果很好。问题是,这个函数只能找到一个子字符串的匹配项。

我的函数如下所示:

    declare -a arrayLog               # This Array contains my Log-File line per line
    declare -a arrayCodeNumber        # Containing the code numbers, e.g. "Command 3"
    declare -a arrayActionTriggered   # Containing the result of the triggered action, e.g. "New street created"

    #[... build arrays etc...]

    function contains() {
    local n=$#
    local value=${!n}
    for ((i=1;i < $#;i++)) {
    shopt -s nocasematch
    [[ "${!i}" =~ "${value^^}" ]] && echo "y;$i" || echo "n;$i"
    }
    }
#I'm calling the function like this in a for-loop:
contains "${arrayLog[@]}" "${arrayCodeNumber[i]}"


    #[... processing function results ...]

我的函数返回 "y;$i" 或 "n;$i" 以指示是否存在匹配项以及在日志文件的哪一行找到匹配项 - 我需要此输出来处理匹配结果稍后在我的代码中。

不幸的是,我不知道如何扩展或改进我的函数以在一行中搜索多个子字符串。

如何扩展函数以接受 2 个输入数组(用于我的匹配参数)和 1 个日志数组并扩展匹配过程?

提前非常感谢!

亲切的问候, 托比

【问题讨论】:

  • 欢迎来到 Stack Overflow!您是否仅限于使用 bash 或者您可以在 shell 中使用其他命令? grep -n "Command 3" log.txt | grep "New street created" | cut -d: -f1 将非常接近您正在寻找的内容

标签: bash substring


【解决方案1】:

考虑这种方法

#!/bin/bash

cmd=('Command 2'        'Command 3')
act=('Street destroyed' 'New street created')

for i in ${!cmd[@]}; {
    grep -no "${cmd[$i]}.*${act[$i]}" file
}

用法

$ ./test
2:Command 2 processed - Street destroyed
1:Command 3 processed - New street created

来自grep帮助

$ grep --help
  ...
  -o, --only-matching       show only the part of a line matching PATTERN
  -n, --line-number         print line number with output lines
  ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 2021-11-28
    • 2014-11-10
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多