将文本添加到特定行linux脚本

时间:2014-10-27 15:50:05

标签: linux sed scripting

我需要创建一个脚本,在文件(XML)中的特定行之后添加文本。以下是我到目前为止的情况:

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>

2 个答案:

答案 0 :(得分:0)

你不能这样做:

any_command file > file

shell将处理重定向 first ,并且在 shell启动命令之前文件将被截断。您现在正在将空文件传递给命令。

有几种技巧:

  1. 如果命令成功完成,则使用临时文件并覆盖原始文件

    temp=$(mktemp)
    any_command file > "$temp" && mv "$temp" file
    
  2. 安装moreutils包并使用sponge命令

    any_command file | sponge file
    

答案 1 :(得分:0)

如果您刚刚收集了所有添加内容,那么程序和问题就会简单得多,然后进行一次替换。

nl='
'
replace="i\\$nl"
while read -p "What should be added? (Empty input to finish) " entry; do
    if [ "$entry" = "" ]; then
        break
    fi
    replace="$replace$nl$entry"
done
sed -i "/<string>/$replace" file