我有一个.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)用于代替起始字符串和结束字符串之间存在的当前内容的字符串。
答案 0 :(得分: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}}
。
答案 1 :(得分:1)
使用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
答案 2 :(得分:0)
Pure 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
repl()函数一次对一行文本起作用,仅当行与字符串匹配时才替换。
Bash没有用于反向引用的机制,这需要冗余。 ${line/%$pre*$suf/$pre$values$suf}
将前缀字符串中的所有内容替换为带有前缀字符串,新值和后缀字符串的后缀。