gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:17 29 4
gpt4 key购买 nike

我需要创建一个脚本,用于在文件 (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>

最佳答案

你不能这样做:

any_command file > file

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

有几种技术:

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

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

    any_command file | sponge file

关于linux - 将文本添加到特定行linux脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591463/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com