bash 将带有特殊字符和换行符的文本附加到文件的特定行

bash append text with special character and newline to file at specific line

我正在尝试将代码文本附加到文件中,代码看起来像

@ReactMethod
public void printBarCode(String str, int nType, int nWidthX, int nHeight,
          int nHriFontType, int nHriFontPosition) {
    byte[] command = PrinterCommand.getBarCodeCommand(str, nType, nWidthX, nHeight, nHriFontType, nHriFontPosition);
    sendDataByte(command);
}

我把它放到一个名为 print_config

的变量中

我所做的是

sed -i "436 i $print_config" $file
# error
sed: -e expression #1, char 25: extra characters after command

我在行尾做了一个“\n”,但它没有换行,而是 @ReactMethod 'n' public void ...

您遇到的问题是 print_config 中包含的文本在文件中有未转义的换行符。具体来说,您正在尝试多行插入:

@ReactMethod
public void printBarCode(String str, int nType, int nWidthX, int nHeight,
          int nHriFontType, int nHriFontPosition) {
    byte[] command = PrinterCommand.getBarCodeCommand(str, nType, nWidthX, nHeight, nHriFontType, nHriFontPosition);
    sendDataByte(command);
}

如果不在每个换行符前加上 '\' 字符,就无法做到这一点。从 man sed 你有 "i \ text Insert text, which has each embedded newline preceded by a backslash."

相反,将上述内容保存到临时文件中,然后使用 r filename 命令到 "Append text read from filename" 可能会更好。在您的情况下,您将拥有:

sed -i '436r tempfile' file_to_modify

这会在第 436 行将 tempfile 的内容读入 file_to_modify,而无需修改文本以使用反斜杠转义每个换行符。