[英]sed replace line with multiline file or variable
I'm retrieving a section from a file and want to replace a line in another file with this multi-line data. 我正在从文件中检索一节,并希望用此多行数据替换另一个文件中的行。 Currently I'm outputting to a file but would prefer to use a variable. 目前,我正在输出到文件,但希望使用变量。
For instance 例如
R 0x00007d04 0x70040000
[OVERWRITE_1]
C "- Starting Execution"
Becomes: 变为:
R 0x00007d04 0x70040000
W 0x00001118 0x0d1f4e3a
W 0x0000111c 0xa3795ac8
W 0x00001120 0xc50e69d5
C "- Starting Execution"
Here is what I have: 这是我所拥有的:
START="R 0x00007fd0 0x00000000 # CSR:014 (CSRCID-OPT2)"
END="W 0x00007f80"
FILE=file.txt
#Retrieve text between sections above to variable
OUTPUT=$(sed -n "/^$START$/,/$END/ { /^$START$/d ; /$END/d ; /^$/d ; p }"
$FILE)
echo "$OUTPUT" > tmp.txt
#This line currently appends after [OVERWRITE_1]
sed '/\[OVERWRITE_1\]/r tmp.txt' test.asm
Which outputs this: 输出以下内容:
R 0x00007d04 0x70040000
[OVERWRITE_1]
W 0x00001118 0x0d1f4e3a
W 0x0000111c 0xa3795ac8
W 0x00001120 0xc50e69d5
C "- Starting Execution"
I know at this point I could remove the line but I feel like others might want to know this also and I haven't found a good solution. 我知道目前可以删除该行,但是我觉得其他人可能也想知道这一点,所以我没有找到一个好的解决方案。
With GNU sed: 使用GNU sed:
Find line in file file.csv which contains find, append content (r) of file newline.txt and delete (d) line which contains find 在包含查找的文件file.csv中查找行,追加文件newline.txt的内容(r),并删除(d)包含查找的行
START="R 0x00007fd0 0x00000000 # CSR:014 (CSRCID-OPT2)"
END="W 0x00007f80"
FILE=file.txt
#Retrieve text between sections above to variable
OUTPUT=$(sed -n "/^$START$/,/$END/ { /^$START$/d ; /$END/d ; /^$/d ; p }"
$FILE)
echo "$OUTPUT" > tmp.txt
sed -e '/\[OVERWRITE_1\]/{r tmp.txt' -e 'd}' test.asm
Sed from variable instead of file : 从变量而不是文件中提取:
START="R 0x00007fd0 0x00000000 # CSR:014 (CSRCID-OPT2)"
END="W 0x00007f80"
FILE=file.txt
#Retrieve text between sections above to variable
OUTPUT=$(sed -n "/^$START$/,/$END/ { /^$START$/d ; /$END/d ; /^$/d ; p }"
$FILE)
echo "$OUTPUT" > tmp.txt
sed "s/\[OVERWRITE_1\]/$OUTPUT/" test.asm
Note that we used double quotes instead of singles. 请注意,我们使用双引号而不是单引号。 But as found here there is a problem if you have special characters inside $OUTPUT (\\, & and /). 但随着发现这里有一个问题,如果你有$ OUTPUT内部特殊字符(\\,与和/)。 Didn't find a good solution for this so I would keep the workaround with the file. 找不到适合的解决方案,因此我将保留该文件的解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.