[英]Replacing a value in a config file
I have a file that looks like: 我有一个看起来像的文件:
my.githash="asdfsadfdsf"
some.key=234
some.blue=abchello
russia.green="asdfdsf"
I want to replace the string for the key my.githash with an up to date git hash vlaue. 我想用最新的git hash vlaue替换密钥my.githash的字符串。
How can I use ruby to update my configuration file? 如何使用ruby更新我的配置文件?
To get the git hash value I will be using: 要获取git hash值,我将使用:
git rev-parse HEAD
Using gsub
you can replace a string using a regular expression match. 使用
gsub
您可以使用正则表达式匹配项替换字符串。 In your case it's a little bit tricky because you don't know exactly the match. 在您的情况下,这有点棘手,因为您不确定确切的匹配。
Hence you can use 因此,您可以使用
string.gsub(/(githash="(.+)")/) { $1.gsub($2, 'NEW_SHA') }
You can fetch the NEW_SHA
running a shell command. 您可以通过运行shell命令来获取
NEW_SHA
。
sha = `git rev-parse HEAD`
string.gsub(/(githash="(.+)")/) { $1.gsub($2, sha) }
and read the file from the file system 并从文件系统中读取文件
sha = `git rev-parse HEAD`
content = File.read('/path/to/fike')
content.gsub!(/(githash="(.+)")/) { $1.gsub($2, sha) }
File.write('/path/to/fike', content)
This is a very simple example. 这是一个非常简单的例子。 You can optimize it further.
您可以进一步优化它。 You can also use a single
gsub
, but it will require you to write twice the delimiters. 您也可以使用一个
gsub
,但是它将要求您编写两次定界符。
content.gsub!(/githash="(.+)"/, %Q{githash="#{sha}"})
Another (longer but perhaps more accurate) way is to write a simple parser that loads the file in a Hash parsing each line (as lines seems to follow a specific syntax), and then dumps the Hash back in a formatted file. 另一种(更长,但也许更准确)的方法是编写一个简单的解析器,将其加载到哈希中以解析每行(因为各行似乎遵循特定的语法),然后将哈希转储回格式化的文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.