How replace variable names in an xml-file?

后端 未结 3 851
执笔经年
执笔经年 2020-12-20 05:56

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.informi         


        
相关标签:
3条回答
  • 2020-12-20 06:08
    sed -e 's/@db.driver@/com.informix.jdbc.IfxDriver/g' -e 's/@db.user.name@/user/g' > outfile.xml
    
    0 讨论(0)
  • 2020-12-20 06:15

    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
    
    0 讨论(0)
  • 2020-12-20 06:24

    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)
    
    0 讨论(0)
提交回复
热议问题