GET变量取代时,我的猫一个文件 [英] get variables substituted when I cat a file

查看:115
本文介绍了GET变量取代时,我的猫一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能,在清洁的方式来获得变量的值时,我的猫文件,而不是变量名,书面的文件中。这很难解释,但在这里不用一个简单的例子:

Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

$ cat <<EOF
$HOME
EOF
/home/myself

猫的报恩/家/我自己,因为它已经由shell扩展。

cat returns /home/myself because it is already expanded by the shell.

$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME

猫只是读取文件,我想$ HOME以某种方式被猫在这里扩大,因为该文件将包含变量名(不喜欢HOME = /家/我自己)

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

我的问题是,如果这是可能以某种方式,否则我将不得不写一些脏code。

My question is if this is possible somehow, otherwise I will have to write some dirty code.

编辑:它们是含有很大的XML文件

they are big xml files containing

<checkbox active="$value">

true或false

true or false

推荐答案

这将是微不足道的Python尝试,看看是否适合你。您可以使用应用re.sub 功能来代替某些模式所有出现像\\ $ \\ W +通过调用一个函数,它不会转变(而不是特定的字符串来取代它)。而对于替换功能,你可以使用 os.getenv(),当然这需要一个变量名,并返回它的值。

This would be trivial to attempt in Python, and see if that works for you. You could use the re.sub function to replace all occurrences of some pattern like "\$\w+" by calling a function which does the transformation (rather than a specific string to replace it with). And for the replacement function you could use os.getenv(), which of course takes a variable name and returns its value.

编辑:下面是一个完整的Python脚本,它上面的:

Here's a complete Python script that does the above:

#!/usr/bin/python

import fileinput
import os
import re

def transform(match):
    return os.getenv(match.group(1)) # replace the "capture" to omit $

for line in fileinput.input(): # reads from stdin or from a file in argv
    print re.sub('\$(\w+)', transform, line), # comma to omit newline

这篇关于GET变量取代时,我的猫一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆