我想更改檔案中縮進的特定標記內的多行字串,示例如下所示:
non_important_array: [
text
],
important_array: [
text1,
text2,
text3
],
non_important_array: [
text
],
我的目標是能夠important_array用我的多行字串替換
my_array: [
my_text1,
my_text2
],
所以我想這樣:
non_important_array: [
text
],
my_array: [
my_text1,
my_text2
],
non_important_array: [
text
],
但也可能有變化,它看起來像這樣:
non_important_array: [text],
important_array: [text1,text2,text3],
non_important_array: [text],
并且輸出應該看起來與上面預期的相似
non_important_array: [text],
my_array: [
my_text1,
my_text2
],
non_important_array: [text],
現在我正在嘗試使用sed它,但它正在最后一次發生,]我不知道如何糾正它
sed -i '' '/\s*important_array.*/,/\]/c\
my_array: [\
my_text1,\
my_text2\
],' file.txt
謝謝!
編輯:
- 一艘班輪將不勝感激
- 我想替換它,修改相同的檔案
uj5u.com熱心網友回復:
使用任何 POSIX awk:
$ cat tst.awk
NR == FNR {
new = new $0 ORS
next
}
/^[[:space:]]*important_array:[[:space:]]*\[/ {
inBlock = 1
printf "%s", new
}
inBlock {
if ( /^[[:space:]]*],/ ) {
inBlock = 0
}
next
}
{ print }
$ awk -f tst.awk file2 file1
non_important_array: [
text
],
my_array: [
my_text1,
my_text2
],
non_important_array: [
text
],
uj5u.com熱心網友回復:
解決方案1:awk腳本:
awk '{sub("[[:space:]]important_array:"," my_array:")}1' ORS="]," RS="]," input.txt
輸出:
non_important_array: [
text
],
my_array: [
text1,
text2,
text3
],
non_important_array: [
text
],
解決方案2:awk腳本:
awk '
BEGIN{ORS="],\n"; RS="],"; FS="\n"; OFS=" "}
{
sub("[[:space:]]important_array:"," my_array:");
gsub("[[:space:]] "," ");
$1=$1;
}1' input.txt
輸出:
non_important_array: [ text ],
my_array: [ text1, text2, text3 ],
non_important_array: [ text ],
uj5u.com熱心網友回復:
-i沒有標志的第一次測驗。
我認為你的問題是\s*,任意數量的空格,所以也匹配non_。
想用sed的時候試試
sed -r '/\s important_array.*/,/\]/c\
my_array: [\
my_text1,\
my_text2\
],' file.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474189.html
