【问题标题】:Bash: Find a pattern and replace what followsBash:找到一个模式并替换以下内容
【发布时间】:2015-03-26 21:45:52
【问题描述】:

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

HelloWorld    (3,4,5)
FooFooFoo     {34,34,34}{23,1,2}
BarFooHello   {{4,5,12}}
BarBar        Bar
HelloFoo      {{6,5}}  

我想在文件中找到字符串 'BarFooHello' 并将直接跟在 'BarFooHello' 之后的起始字符串 '{{' 和结束字符串 '}}' 之间的任何内容替换为 '12,12,12, 12'。目标是获取一个文件这个文件最后:

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) 字符串来代替存在于起始字符串和结束字符串之间的当前内容。

【问题讨论】:

  • awk 或 sed 怎么样?

标签: regex string bash file


【解决方案1】:
$ 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 循环遍历文件中的每一行。

  • /^BarFooHello/

    这只会选择以BarFooHello 开头的行。

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

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

【讨论】:

  • 有一天我一定要了解更多关于 Bash 的知识。这样的功能非常方便。感谢您的回答。我感谢简短的解释 +1
【解决方案2】:

使用 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

【讨论】:

    【解决方案3】:

    纯猛击:

    #!/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
    

    repl() 函数一次处理一行文本,并且仅当该行与字符串匹配时才进行替换。

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

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2012-01-25
      • 2018-09-07
      • 2013-08-24
      • 1970-01-01
      • 2017-10-22
      相关资源
      最近更新 更多