[英]Bash: Find a pattern and replace what follows
我有一個.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)替換存在於其中的當前內容的字符串在起始字符串和結束字符串之間。
$ 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
開頭的BarFooHello
。
s/{{.*}}/{{12,12,12,12}}/
在這些選定的行上,這將替換該行的第一個{{
和最后一個}}
之間的所有內容,並將其替換為{{12,12,12,12}}
。
使用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
純重擊:
#!/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}
用前綴字符串,新值和后綴字符串替換從前綴字符串到后綴的所有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.