我在Linux中有一个配置文件(xml),我正在尝试将其他学生添加到student_names Configuration_item(如果不存在) 例如,如果我得到唐纳德,我不需要做任何事情,因为它在那里 如果我得到汤姆,我需要添加它,因为它不存在
<Configuration_item Key="foo" Value="bar"/>
<Configuration_item Key="students_names" Value="Todd;Marry;Alen;Donald"/>
<Configuration_item Key="foo2" Value="baz/>
继续使用XML
解析器会更好,但是bash
可以在xml
文件很简单的情况下执行此操作。不是一个很好的解决方案,但它可以做到这一点。
#!/bin/bash
infile="$1"
name="$2"
while IFS='' read -r line || [[ -n "$line" ]]; do
case $line in
*students_names*)
case $line in
*"$name"\;*|*"$name"\"*) echo "$line" ;;
*) echo "${line//Value=\"/Value=\"$name;}" ;;
esac ;;
*) echo "$line" ;;
esac
done < "$infile"
该脚本逐行读取并解析输入的example.xml
文件。它应用变量扩展来匹配目标线(包含Key="students_names"
)并确定它是否包含$name
。如果与$name
不匹配则添加它,否则打印该行。
例1:
./add_value.sh example.xml Todd
输出:
<Configuration_item Key="foo" Value="bar"/>
<Configuration_item Key="students_names" Value="Todd;Marry;Alen;Donald"/>
<Configuration_item Key="foo2" Value="baz/>
例2:
./add_value.sh example.xml Toddy
输出:
<Configuration_item Key="foo" Value="bar"/>
<Configuration_item Key="students_names" Value="Toddy;Todd;Marry;Alen;Donald"/>
<Configuration_item Key="foo2" Value="baz/>