shell 中的多行替換

shell 中的多行替換

我的文字檔案中有以下文字區塊:

* Exported from Foo *

Title and Section

和另一個

* Exported from Foo *

Other Title and Other Section

我需要將其替換為

# Title and Section

# Other Title and Other Section

現在,我可以這樣做:

echo "$(grep -A 2 "Exported from Foo" ../tmp/data/${nospacefile} | grep -v "Exported from Foo" | grep -v -- -- | tr -d '\r' | grep -v -e '^[[:space:]]*$' | sed -e 's/^[ \t]*//')" | while read -r title; do sed -i -e "s/^\([[:blank:]]*\)$title/\# $title/g" ../tmp/data/${nospacefile}; done

但是,字串“標題和部分”或“其他標題和其他部分”也出現在我不想替換的地方。我只希望它出現在匯出行和空白行之後時被替換。

對我來說,執行此操作的最佳 shell 結構是什麼?我非常樂意將標準輸出發送到 perl、python 等。

答案1

您可以嘗試,無論第二行是否為空,都ed(1)從第三行開始編輯。* Exported from Foo *

只列印輸出像stdoutsed

printf '%s\n' 'g/^\* Exported from Foo \*$/+2s/^/# /' ,p Q | ed -s file.txt 

這只是將輸出列印到stdout,以便就地編輯文件。

printf '%s\n' 'g/^\* Exported from Foo \*$/+2s/^/# /' w | ed -s file.txt 

使用ed僅將輸出列印到的腳本stdout

cat script.ed

輸出

g/^\* Exported from Foo \*$/+2s/^/# /
,p
Q

編輯文件的腳本in-place

g/^\* Exported from Foo \*$/+2s/^/# /
w
q

現在你可以做

ed -s file.txt < script.ed

相關內容