Regex Bash:找到一个模式并替换下面的内容

Regex Bash:找到一个模式并替换下面的内容,regex,string,bash,file,Regex,String,Bash,File,我有一个.txt文件,如下所示: HelloWorld (3,4,5) FooFooFoo {34,34,34}{23,1,2} BarFooHello {{4,5,12}} BarBar Bar HelloFoo {{6,5}} 我想在文件中找到字符串“BarFooHello”,并用“12,12,12,12”替换直接跟在“BarFooHello”后面的起始字符串“{{”和结束字符串“}}}”之间的任何内容。目标是获得一个文件,该文件在最后: He

我有一个.txt文件,如下所示:

HelloWorld    (3,4,5)
FooFooFoo     {34,34,34}{23,1,2}
BarFooHello   {{4,5,12}}
BarBar        Bar
HelloFoo      {{6,5}}  
我想在文件中找到字符串“BarFooHello”,并用“12,12,12,12”替换直接跟在“BarFooHello”后面的起始字符串“{{”和结束字符串“}}}”之间的任何内容。目标是获得一个文件,该文件在最后:

HelloWorld    (3,4,5)
FooFooFoo     {34,34,34}{23,1,2}
BarFooHello   {{12,12,12,12}}
BarBar        Bar
HelloFoo      {{6,5}}  
如何在Bash中实现这一点?我希望在Bash中有一个函数,它接受1)起始字符串2)结束字符串,3)执行修改后的字符串,以及4)替换起始字符串和结束字符串之间的当前内容的字符串

$ sed '/^BarFooHello/ s/{{.*}}/{{12,12,12,12}}/' file.txt
HelloWorld    (3,4,5)
FooFooFoo     {34,34,34}{23,1,2}
BarFooHello   {{12,12,12,12}}
BarBar        Bar
HelloFoo      {{6,5}}  
工作原理
sed
循环文件中的每一行

  • /^barfoohhello/

    这仅选择以
    barfoohhello
    开头的行

  • s/{{.*}/{{12,12,12,12}}/

    在这些选定的行上,这将替换该行上第一个
    {{
    和最后一个
    }
    之间的所有内容,并将其替换为
    {12,12,12}

    • 纯Bash:

      #!/bin/bash
      
      repl () {
          line="$1"
          str="$2"
          pre="$3"
          suf="$4"
          values="$5"
      
          if [[ $line =~ ^$str ]]; then
            line="${line/%$pre*$suf/$pre$values$suf}"
          fi
          echo "$line"
      }
      
      while read line; do
         repl "$line" BarFooHello "{{" "}}" 12,12,12,12
      done < file
      
      #/bin/bash
      repl(){
      第行=“1美元”
      str=“$2”
      pre=“$3”
      suf=“$4”
      值=“$5”
      如果[[$line=~^$str]];则
      line=“${line/%$pre*$suf/$pre$values$suf}”
      fi
      回音“$line”
      }
      读行时;做
      repl“$line”barfooholl“{{”“}}”12,12,12,12
      完成<文件
      
      repl()函数一次处理一行文本,仅当该行与字符串匹配时才替换


      Bash没有用于反向引用的机制,这需要冗余<代码>${line/%$pre*$suf/$pre$values$suf}用前缀字符串、新值和后缀字符串替换从前缀字符串到后缀的所有内容

      使用sed,您可以:

      funct ()
      {
      start=$1  # "BarFooHello"
      begin=$2  # "{{"
      end=$3    # "}}"
      string=$4 # "12,12,12,12"
      file=$5   # The file to perform the replacement
      
      sed "s/^$start   $begin[[:print:]]*$end/$start   $begin$string$end/g"  $file # Sensitive to 3 spaces
      # or
      sed "s/^$start\(\ *\)$begin[[:print:]]*$end/$start\1$begin$string$end/g"  $file  # Preserve the amount of spaces
      }
      
      用起来像这样:

      funct "BarFooHello" "{{" "}}" "12,12,12,12" test.txt
      

      那awk和sed呢?总有一天我一定要学习更多关于Bash的知识。这些功能非常方便。谢谢你的回答。我感谢你简短的解释