使用 sed 替換包含換行符號的內容

使用 sed 替換包含換行符號的內容

我有 markdown README 文件,其中有這樣的 html 標記:

<!-- CONTRIBUTORS-START -->
<!-- CONTRIBUTORS-END -->

我想用帶有 html 標籤和換行符的文件中的新內容替換裡面的文本(它可能已經有東西了)(它是單元格中帶有 html 的 markdown 表)。

我試圖將 sed 中的換行符號替換為 0xFF ,然後使用以下程式碼將其替換回來:

CONTRIBUTORS=`./contributors -u jcubic -r jquery.terminal -m | tr '\n' $'\xFF'`
# contributors script get data from github and display markdown table
# or ERROR if rate limit reached

echo "$CONTRIBUTORS" | grep ERROR > /dev/null || cat README.in | tr '\n' $'\xFF' | \
    sed -e "s%\(<!-- CONTRIBUTORS-START -->\).*\(<!-- CONTRIBUTORS-END -->\)%\1\n${CONTRIBUTORS}\2%" #| tr $'\xFF' '\n'

但這不起作用,如何用貢獻者內容替換標記內的文字?

當我使用時它有點工作tr '\n' '\xFF',但它正在用 替換換行符x

我找到這篇文章Sed:兩種模式之間的多行替換並嘗試使用:

sed -n "/CONTRIBUTORS-START/{p;:a;N;/CONTRIBUTORS-END/!ba;s%.*\n%${CONTRIBUTORS}\n%};p"

(我已在 s 命令中將 / 替換為 % )但出現錯誤:

sed: -e expression #1, char 1630: unterminated `s' command

答案1

我使用了這個 hack,我只是將新行轉換為笑臉 Unicode 字符"☺",同時進行 sed 替換,因為換行符引起了問題。

CONTRIBUTORS=`./contributors -u jcubic -r jquery.terminal -m $@  | tr '\n' '☺'`

if echo "$CONTRIBUTORS" | grep ERROR > /dev/null; then
    echo "$CONTRIBUTORS" | tr '☺' '\n'
else
    cat README.in | sed -n "/CONTRIBUTORS-START/{p;:a;N;/CONTRIBUTORS-END/!ba;s%.*\n%${CONTRIBUTORS}%};p" | tr '☺' '\n' > README.tmp
    cp README.tmp README.in
    rm README.tmp
fi

相關內容