我正在从一个文件中检索一个部分,并想用这个多行数据替换另一个文件中的一行。目前我正在输出到文件,但更愿意使用变量。
例如
R 0x00007d04 0x70040000
[OVERWRITE_1]
C "- Starting Execution"
变成:
R 0x00007d04 0x70040000
W 0x00001118 0x0d1f4e3a
W 0x0000111c 0xa3795ac8
W 0x00001120 0xc50e69d5
C "- Starting Execution"
这是我的:
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
输出这个:
R 0x00007d04 0x70040000
[OVERWRITE_1]
W 0x00001118 0x0d1f4e3a
W 0x0000111c 0xa3795ac8
W 0x00001120 0xc50e69d5
C "- Starting Execution"
我知道此时我可以删除该行,但我觉得其他人可能也想知道这一点,但我还没有找到好的解决方案。
最佳答案
找到解决方案 here
With 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
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
从变量而不是文件中获取
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
请注意,我们使用双引号而不是单引号。 但是发现here如果 $OUTPUT 中有特殊字符(\、& 和/),就会出现问题。没有为此找到好的解决方案,所以我会保留文件的解决方法。
关于linux - sed 用多行文件或变量替换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896612/