如何在 bash 脚本中用多个 line/stream 替换单个 stream/line?

How to replace a single stream/line with multiple line/stream in bash scripting?

我对此很陌生,所以请多多包涵。 :( 在 android 的 bash 脚本中,我试图用存储在另一个 xml 文件中的另一组 stream/line 替换单个 fonts.xml 流,该行是:


    <family name="sans-serif">

我试图用它替换的是:(存储在另一个 xml 文件中)


    <family name="sans-serif">
        <font weight="100" style="normal">Thin.ttf</font>
        <font weight="100" style="italic">ThinItalic.ttf</font>
        <font weight="300" style="normal">Light.ttf</font>
        <font weight="300" style="italic">LightItalic.ttf</font>
        <font weight="400" style="normal">Regular.ttf</font>
        <font weight="400" style="italic">Italic.ttf</font>
        <font weight="500" style="normal">Medium.ttf</font>
        <font weight="500" style="italic">MediumItalic.ttf</font>
        <font weight="700" style="normal">Bold.ttf</font>
        <font weight="700" style="italic">BoldItalic.ttf</font>
        <font weight="900" style="normal">Black.ttf</font>
        <font weight="900" style="italic">BlackItalic.ttf</font>
    </family>
    <family>

目标是通过 magisk 模块使用自定义字体作为默认的第一种字体,并将 Roboto 作为后备。如何用 sed 将第一个流替换为预期的流集。我尝试了几种基本的 sed 但 none 似乎有效!

如果你真的想为此使用 sed,你可以尝试这个实现,它用新行 (\n) 替换未使用的字符 (%),执行替换,然后恢复新行。

#!/bin/bash

multi_line_sed()
{
    local find_str=""
    local replace_str=""
    local unused_char="%"

    # 1. substitute out new lines (for stdin and function arguments)
    # 2. perform replacement
    # 3. restore new lines

    find_str=$(printf "$find_str" | tr "\n" "$unused_char")
    replace_str=$(printf "$replace_str" | tr "\n" "$unused_char")

    tr "\n" "$unused_char" |
    sed "s|${find_str}|${replace_str}|g" |
    tr "$unused_char" "\n"
}

file="fonts.xml"

find_str="<family name=\"sans-serif\">"
replace_str="$(cat custom_font.xml)"

cat "$file" | multi_line_sed "$find_str" "$replace_str"