ruby Puppet 中的字符串替换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10418104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:05:36  来源:igfitidea点击:

String substitution in Puppet?

rubypuppet

提问by richardkmiller

Is it possible to do a string substitution/transformation in Puppet using a regular expression?

是否可以使用正则表达式在 Puppet 中进行字符串替换/转换?

If $hostname is "web1", I want $hostname_without_number to be "web". The following isn't valid Puppet syntax, but I think I need something like this:

如果 $hostname 是“web1”,我希望 $hostname_without_number 是“web”。以下不是有效的 Puppet 语法,但我想我需要这样的东西:

$hostname_without_number = $hostname.gsub(/\d+$/, '')

回答by freiheit

Yes, it is possible.

对的,这是可能的。

Check the puppet function reference: http://docs.puppetlabs.com/references/2.7.3/function.html

查看puppet函数参考:http: //docs.puppetlabs.com/references/2.7.3/function.html

There's a regular expression substitution function built in. It probably calls the same underlying gsub function.

有一个内置的正则表达式替换函数。它可能调用相同的底层 gsub 函数。

$hostname_without_number = regsubst($hostname, '\d+$', '')

Or if you prefer to actually call out to Ruby, you can use an inline ERB template:

或者,如果您更喜欢实际调用 Ruby,则可以使用内联 ERB 模板:

$hostname_without_number = inline_template('<%= hostname.gsub(/\d+$/, "") %>')

回答by user45949

In this page:

在此页面中:

https://blog.kumina.nl/2010/03/puppet-tipstricks-testing-your-regsubst-replacings-2/comment-page-1/

https://blog.kumina.nl/2010/03/puppet-tipstricks-testing-your-regsubst-replacings-2/comment-page-1/

it is quite well explained and there is a fantastic trick for testing your regular expressions with irb.

它解释得很好,并且有一个很棒的技巧可以使用 irb 测试您的正则表达式。

Whith this link and the answer of freiheit I could resolve my problem with substitution of '\' for '/'.

通过此链接和 freiheit 的答案,我可以通过将 '\' 替换为 '/' 来解决我的问题。

$programfiles_sinbackslash = regsubst($env_programfiles,'\','/','G')

$programfiles_sinbackslash = regsubst($env_programfiles,'\','/','G')