如何解决bash 将带有特殊字符和换行符的文本附加到文件的特定行
我试图将代码文本附加到文件中,代码看起来像
@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
这会将 tempfile
的内容读入 file_to_modify
第 436
行,而无需修改文本以使用反斜杠对每个换行符进行转义。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。