Ruby中的Sed问题
我正在尝试更新工作中的站点生成器。必须做的事情之一是编辑gitosis.conf文件,将repo添加到正确的组中。这就是当前在gitosis.conf文件中设置该块的方式Ruby中的Sed问题,ruby,sed,Ruby,Sed,我正在尝试更新工作中的站点生成器。必须做的事情之一是编辑gitosis.conf文件,将repo添加到正确的组中。这就是当前在gitosis.conf文件中设置该块的方式 [group sites] writable = site1 site2 site3 randomsite awesomeness members = @devs 因此,经过无数次尝试,我取得了一些“进步”,然后又后退了一些 sed -i"" -e"/sites/,\$s/writable.*/& PROJECTNA
[group sites]
writable = site1 site2 site3 randomsite awesomeness
members = @devs
因此,经过无数次尝试,我取得了一些“进步”,然后又后退了一些
sed -i"" -e"/sites/,\$s/writable.*/& PROJECTNAME/" gitosis.conf
我终于能够让代码在CentOS命令行上运行,但现在如果我尝试在irb中运行它(在带有backticks的ruby脚本中运行它,因此这必须起作用),我会遇到以下错误:
sed:-e表达式#1,字符22:未知命令:`&'
=>“”
“char 22”可能是不正确的,因为我对其中的一些单词进行了一些编辑,使示例更简单
这就是ruby脚本中的实际内容
gitosis = `sed -i"" -e"/sites/,\$s/writable.*/& PROJECTNAME/" gitosis.conf`
我一直在到处寻找,试图解决这个问题,但到目前为止,我什么也没找到。我在很多地方读到过,为了保持ruby,更好的选择是ruby-pe,但我甚至不知道从哪里开始。任何建议/意见都会很棒。谢谢大家! 你可以用
sed
来做,如果你不能用其他方法做,你可以不用&
来做,比如:
gitosis = `sed -i"" -e"/plexus/,\$s/\(writable.*\)/\1 #{projectname}/" gitosis.conf`
但是使用
ruby
你可以.ini
文件,你的ruby脚本在没有sed
的情况下也可以工作 您实际上不需要转义$
变量。试试这个-
gitosis=sed-i”“-e”/70/,/$/s/75/&{p}/“gitosis.conf
或
gitosis=sed-i”“-e”/70/,$s/75/&{p}/“gitosis.conf
虽然我不太确定您计划如何处理分配此
sed one liner的变量。由于它是一个行内替换
,因此您将得到一个没有任何内容的变量 这是未经测试的代码,是动态编写的,但应该让您开始使用纯Ruby解决方案:
# [group sites]
# writable = site1 site2 site3 randomsite awesomeness
# members = @devs
FILENAME = 'gitosis.conf'
# bail if the group is missing from the command line
abort('Missing group to add') if (ARGV.empty?)
# read the file
contents = File.read(FILENAME)
# find and extract the "writable" line
writable = contents[/^writable.+$/]
# open the new file. This will automagically close it when done.
File.open("#{FILENAME}.new", 'w') do |fo|
# output the current file, replacing the current writable line with one containing the old
# contents with the added new group followed by a line-ending.
fo.print contents.sub(writable, writable + ' ' + ARGV.shift + "\n")
end
# add code here to handle moving/deleting/something with the old file and
# moving the new file into place.
我有点困惑为什么你不在Ruby中完成所有工作?我刚刚在bash中完成了类似的工作,所以我尝试将我的旧脚本转换到现有的站点生成器中。好吧,我来试一试。我会让你知道结果是什么!它可以工作,但代码会按原样在等号(writable PROJECTNAME=…)之前添加文本。不过我把它修好了!我不打算用这个变量做任何事情,只是为了让我自己保持事情的正确性。非常感谢。哦,好的。是的,因为变量没有任何内容。但是,如果变量为空,我不确定您是否计划使用该变量作为测试条件来执行一些后续操作。但我很高兴一切顺利!:)