【发布时间】:2019-10-22 18:15:30
【问题描述】:
如果内容有新行并且此内容由函数生成,则无法在匹配行之前添加行
另一个看起来不错的替代方案 (Insert multiple lines into a file after specified pattern using shell script) 但它只附加了“AFTER”。我需要“之前”
然后将xml内容放入add.txt
sed '/4/r add.txt' $FILE
#/bin/sh
FILE=/tmp/sample.txt
form_xml_string()
{
echo "<number value=\"11942\">"
echo " <string-attribute>\"hello\"</string-attribute>"
echo "</number>"
}
create_file()
{
if [ -e $FILE ]
then
echo "Removing file $FILE"
rm $FILE
fi
i=1
while [ $i -le 5 ]
do
echo "$i" >> $FILE
i=$(( i+1 ))
done
}
create_file
cat $FILE
# file sample.txt has numbers 1 to 5 in each line
# Now append the content from form_xml_string to line before 4
# command I tried
CONTENT=`form_xml_string`
echo "CONTENT is $CONTENT"
sed -i "/4/i $CONTENT" $FILE
cat $FILE
预期输出:
1
2
3
<number value="11942">
<string-attribute>"hello"</string-attribute>
</number>
4
5
实际输出(或错误): sed:-e 表达式 #1,字符 31:未知命令:`
【问题讨论】:
-
可能是我遗漏了一些东西,但
sed -i "/4/i $CONTENT" $FILE已经做了你想做的事情(在给定的匹配模式之前插入行)......那么这里真正的问题是什么?跨度> -
忘记添加“实际输出”:这是:sed: -e expression #1, char 31: unknown command: `