【问题标题】:bash Check for block of textbash 检查文本块
【发布时间】:2014-09-02 15:49:33
【问题描述】:

如果存在文本块,我想执行一个命令,即

if [ multiple line string exists ]; then
   <execute command>
fi

有问题的多行字符串之一是以下所有内容:

Which test would you like to run? 3

        [led.test]
        : This test will light LEDs 1 and 2
        :
        : LED1     LED2
        : --------------
        : ON       OFF
        : OFF      ON
        :
------> : Did the LEDs light up as indicated above? (y/n):n:
FAILED  : User indicates LEDs did not light up properly

正则表达式可用于某些文本,但我需要确保此失败与此测试相对应。 FAILED 行对于所有 LED 测试都很常见,因此我希望只搜索确切的文本块。

如何搜索多行字符串?我正在考虑将该字符串放入变量中,例如

string1="    Which test would you like to run? 3

        [led.test]
        : This test will light LEDs 1 and 2
        :
        : LED1     LED2
        : --------------
        : ON       OFF
        : OFF      ON
        :
------> : Did the LEDs light up as indicated above? (y/n):n:
FAILED  : User indicates LEDs did not light up properly"

然后以某种方式检查 string1 是否在文件中。如果它存在,那么我将执行一个命令,例如echo "字符串存在"

【问题讨论】:

  • 你的问题是什么?
  • @AmalMurali 我正在尝试编写一个条件语句来搜索文件中的多行字符串,但我无法做到。
  • 好的,但是你到底想做什么? “编写条件语句以在文件中搜索多行字符串”描述性不够;至少对我来说。
  • 恕我直言,您需要匹配此类字符串的设计并不是最好的。再次尝试重新思考问题,并选择更好的方法。无论如何,多行匹配是可能的,例如使用perl
  • if [[ $(&lt;file.txt) = *"$string1"* ]]; then ...

标签: regex string bash multiline


【解决方案1】:

将整个文件读入 shell 并进行模式匹配效率低下,但在 grep 不匹配的情况下可以正常工作:

if [[ $(<file.txt) = *"$string1"* ]]; then

【讨论】:

  • 对于需要root权限才能读取的文件:$(sudo cat file.txt)
【解决方案2】:

这样的事情怎么样?

string1="Which test would you like to run? 3

    \[led.test\]
    : This test will light LEDs 1 and 2
    :
    : LED1     LED2
    : --------------
    : ON       OFF
    : OFF      ON
    :
------> : Did the LEDs light up as indicated above? \(y/n\):n:
FAILED  : User indicates LEDs did not light up properly"

#Search the file for the string1 and assign the matching parts to search
search=`grep "${string1}" file.txt`

#If the string existed in the file, then search and string1 should match EXACTLY
if [ "${search}" = "${string1}" ]; then
    #DO STUFF 
    echo "string exists"
fi

只有当 string1 与文件中的内容完全一致并且没有重复项时,这才有效。如果有重复项,您可以通过uniq 传递grep 结果。

编辑: 正如 Charles Duffy 指出的那样,您必须小心任何可能被视为正则表达式的符号。你可以简单地用 '\' 转义它们

【讨论】:

  • 使用grep -q 比使用grep 更好——效率更高,因为它会在找到匹配项后立即停止,而不是继续到文件末尾——并检查退出状态,不是输出。
  • grep 将您的字符串视为正则表达式或(如在 fgrep 模式中)作为模式列表而不仅仅是一个模式也存在危险。例如,[led.test] 匹配led.t 中的任何单个字符
  • 是的,你是对的。 grep 确实与 [] 混淆了
  • -q 会很有效,但是它不能与多行字符串一起正常工作,即它会在多行字符串的第一个匹配行处停止。
  • 如果grep -q 这样做,那么检查grep 是否在多行匹配中输出任何内容同样会失败——如果任何行匹配,它将有 some 输出。类似地,如果它包含要匹配的文本但其他内容还匹配多行字符串的任何单行,则会得到假阴性。如果你有匹配的内容,但它们之间有其他行,你会得到一个你不应该有的误报匹配。
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 2014-12-23
  • 1970-01-01
  • 2013-03-02
  • 2013-09-06
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多