How replace variable names in an xml-file?

2020-02-13 05:12发布

The java build tool ant provides filter to replace variables by their values

Example: A file with properties:

db.user.name=user
db.driver=com.informix.jdbc.IfxDriver

A XML file with generic settings (Note the @variables@ )

<driver-class>@db.driver@</driver-class>
<user-name>@db.user.name@</user-name>

becomes after coping using the filter

<driver-class>com.informix.jdbc.IfxDriver</driver-class>
<user-name>user</user-name>

How can this functionallity be achieved with bash and plain unix tools?

3条回答
别忘想泡老子
2楼-- · 2020-02-13 05:40

This is an other implementation using bash only. If you can take the python version for you need I would suggest that. It will be easier to maintain. Otherwise you could try with this bash script:

#!/bin/bash

config="$1"
xml="$2"

tmp=$(mktemp)

cat "$config" | while read line; do

    key=`echo $line | sed -n 's/^\([^=]\+\)=\(.*\)$/\1/p'`
    value=`echo $line | sed -n 's/^\([^=]\+\)=\(.*\)$/\2/p'`

    echo " sed 's/@$key@/$value/g' | " >> $tmp
done
replacement_cmd=`cat $tmp`
eval "cat \"$xml\" | $replacement_cmd cat"

rm -f $tmp
查看更多
Anthone
3楼-- · 2020-02-13 05:45

You can do it with a very short script in pretty much any language - here's an example in Python:

#!/usr/bin/env python

import sys, re

if len(sys.argv) != 3:
    print "Usage: %s <mapping-file> <input-file>" % (sys.argv[0],)
    sys.exit(1)

mapping_file, input_file = sys.argv[1:]

mapping = {}

with open(mapping_file) as fp:
    for line in fp:
        m = re.search(r'^(.*?)=(.*)$',line)
        if m:
            mapping[m.group(1).strip()] = m.group(2).strip()

def replace_from_mapping(m):
    return mapping.get(m.group(1), m.group(0))

with open(input_file) as fp:
    text = fp.read()
    text = re.sub(r'@(.*?)@', replace_from_mapping, text)
    sys.stdout.write(text)
查看更多
何必那么认真
4楼-- · 2020-02-13 05:47
sed -e 's/@db.driver@/com.informix.jdbc.IfxDriver/g' -e 's/@db.user.name@/user/g' > outfile.xml
查看更多
登录 后发表回答