我需要創建一個腳本,它將在文件(XML)中的特定行之後添加文本。這是我到目前爲止:將文本添加到特定的行linux腳本
echo
echo "This script will blah blah blah"
echo
read -p "Press Enter to continue..."
clear
var1=`grep -n "<string>" <file> | awk -F ":" '{print $1}'` //var1 = line number
function EnterID()
{
echo -n "Enter ID: "
read ID
var2="text to be added"
sed "$((var1+1))i$var2" <file> > <file> //add text to file, overwrite file
#var1="$((var1+1))" //increment line number???
echo
echo "ID successfully added to file"
echo
EnterNewID
}
EnterNewID()
{
read -p "Press Enter to continue..."
clear
echo -n "Would you like to add another ID? (y)es or (n)o: "
read answer
clear
if [ $answer = "y" ]; then
EnterID
else
exit
fi
}
EnterID
該腳本第一次工作。但是,如果用戶嘗試添加附加ID,則第一個ID將被覆蓋。我也應該說我不是程序員(更多的是網絡人員)。我有一點經驗腳本,但僅此而已。
其它信息:
原件:
<SubscriberXML>
<Subscribers>
<Subscriber address="0.0.0.0" id="1" />
<Subscriber address="0.0.0.0" id="2" />
<Subscriber address="0.0.0.0" id="3" />
<Subscriber address="0.0.0.0" id="4" />
<Subscriber address="0.0.0.0" id="5" />
</Subscribers>
</SubscriberXML>
初次使用後:
第二使用<SubscriberXML>
<Subscribers>
<Subscriber address="0.0.0.0" id="X" /> // newly added ID
<Subscriber address="0.0.0.0" id="1" />
<Subscriber address="0.0.0.0" id="2" />
<Subscriber address="0.0.0.0" id="3" />
<Subscriber address="0.0.0.0" id="4" />
<Subscriber address="0.0.0.0" id="5" />
</Subscribers>
</SubscriberXML>
後:
<SubscriberXML>
<Subscribers>
<Subscriber address="0.0.0.0" id="Y" /> // newly added ID
<Subscriber address="0.0.0.0" id="1" />
<Subscriber address="0.0.0.0" id="2" />
<Subscriber address="0.0.0.0" id="3" />
<Subscriber address="0.0.0.0" id="4" />
<Subscriber address="0.0.0.0" id="5" />
</Subscribers>
</SubscriberXML>
想要:
<SubscriberXML>
<Subscribers>
<Subscriber address="0.0.0.0" id="Y" />
<Subscriber address="0.0.0.0" id="X" />
<Subscriber address="0.0.0.0" id="1" />
<Subscriber address="0.0.0.0" id="2" />
<Subscriber address="0.0.0.0" id="3" />
<Subscriber address="0.0.0.0" id="4" />
<Subscriber address="0.0.0.0" id="5" />
</Subscribers>
</SubscriberXML>
嗨,你能提供一個你想覆蓋的文件的例子,以及預期的結果嗎?這將有所幫助。 – Matt 2014-10-27 16:14:24
當然有一點 – dej27 2014-10-27 16:33:06
我建議你在這裏使用一些xml處理工具,而不是sed和awk的combinator。你見過xmlstarlet工具嗎? https://stackoverflow.com/questions/5591414 – marbu 2014-10-27 16:59:50