使用shell脚本将文本附加到XML文件中的节

问题描述 投票:-1回答:1

我在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/>
shell
1个回答
3
投票

继续使用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/>
© www.soinside.com 2019 - 2024. All rights reserved.