我要添加下面的行到〜/ .bashrc中:检查文件中是否存在一条特定行?
export PATH:/var/lib/gems/1.9.1/bin:$PATH
但只有当它不存在。
如何检查该行是否已经存在?
我要添加下面的行到〜/ .bashrc中:检查文件中是否存在一条特定行?
export PATH:/var/lib/gems/1.9.1/bin:$PATH
但只有当它不存在。
如何检查该行是否已经存在?
这可能吗?
File.open(".bashrc").each_line do |line|
if (line == "foo")
return true
end
end
return false
path_seen = false
File.open(~/.bashrc) do |f|
f.grep(/export PATH:\/var\/lib\/gems\/1.9.1\/bin:\$PATHg/) do |line|
path_seen = true
end
end
你提的问题大概意思是说:
export PATH=/var/lib/gems/1.9.1/bin:$PATH
(注意第一个 ':' 应该是一个 '=')
此外,在创建正则表达式时许多'/'(根据@ennuikiller的解决方案),您可能会喜欢使用%r {}构造函数而不是//。例如:
f.grep(/export PATH:\/var\/lib\/gems\/1.9.1\/bin:\$PATHg/) do |line|
变得读取容易(轻微修正 - 移除的后“G”):
f.grep(%r{export PATH:/var/lib/gems/1.9.1/bin:\$PATH}) do |line|
由于回车是在这个时代供不应求.. 。
return File.open('.bashrc').lines.any? { |line| line.chomp == 'foo'}
我只是碰到了这个问题来找检查一个特定的Rails的路线已经存在:
route = "mount Blorgh::Engine"
File.open('config/routes.rb').each_line.any? {|line| line[/#{route}/] }