搜索并替换文件中的字符串

时间:2014-08-24 23:26:13

标签: linux unix

我正在尝试使用此方案创建一个unix脚本:

我的主配置文件包含以下行:

#BEGIN mytest
#END mytest

我的输入文件有:

location /server/ {
                  (proxy config here) 
                 }

我想创建一个搜索#BEGIN mytest的脚本,如果找到添加包含我的输入文件的另一行,输出将如下:

#BEGIN mytest
location /server/ {
                  (proxy config here) 
                 } 

#END mytest

2 个答案:

答案 0 :(得分:1)

使用r中的sed(读取文件)命令:

sed -e '/#BEGIN mytest/r input' config 

答案 1 :(得分:0)

规范不一致。你写'搜索'#BEGIN mytest“',但给定的输出缺少'#'。我假设'#'是注释字符,您希望配置文件包含#BEGIN mytest#END mytest的评论文本。鉴于此,以下ruby脚本将起到作用:


#!/usr/bin/env/ruby
# update-cfg-file CFGFILE [NAME FILE] ...
#
# read CFGFILE and look for occurrences of '#BEGIN NAME', and (replace and)
# insert the contents of FILE2 inline into CFGFILE.  all the original text (if
# any) from CFGFILE up to #END NAME' will be replaced by FILE2.
#
# Multiple occurrences of NAME FILE may be given, each unique name being
# associated with the contents of the subsequent FILE.
#
# if there are no occurrences of '#BEGIN NAME' within CFGFILE, no changes are
# made.  If there are changes, the previous copy of CFGFILE is retained as
# CFGFILE.TIMESTAMP, where TIMESTAMP is YYYY-MM-DD.HH.MM.SS

cfgfile_name = ARGV.shift || raise "No CONFIGFILE argument"

def talk msg
  $stderr.puts msg
end

files = {}
while ARGV.size > 0 do
  name = ARGV.shift
  name_file = ARGV.shift
  break if name.empty? || name_file.empty?
  if !File.exist? name_file
    raise "#{name_file} does not exist"
  end
  files[name] = name_file
end

if files.size == 0
  raise "No NAME FILE pairs given"
end

new_cfgfile = cfgfile + '.new'

cfgin = open(cfgfile, 'r')
cfgout = open(new_cfgfile, 'w')

name_re = files.keys.join('|')

changes = false
while line = cfgin.gets do
  cfgout.puts line                              # output the line
  if line =~ /^#\s*BEGIN\s+(#{name_re})\>/      # was it a boundary?
    matched_name = $1
    if files.key?(matched_name)                 # one of our keys?
      talk "Found #{matched_name}"
      while end_line = cfgin.gets do            # skip until the closing boundary
        break if end_line =~ /^#\s*END\s+#{matched_name}/
      end
      talk "Inserting #{name_cfg} ..."
      open(files[matched_name]) do |name_cfg|   # copy file into cfgout
        while cfgline = name_cfg.gets
          cfgout.puts cfgline
          changes = true
        end
      end
      cfgout.puts end_line                      # output the end_line
    end
  end
end
cfgin.close
cfgout.close

if changes
  talk "There were changes."
  timestamp = Date.now().strftime("%F_%H.%M.%S")
  talk "#{cfgfile} saved with suffix of #{timestamp}"
  File.rename(cfgfile, cfgfile + ".#{timestamp}")
  talk "#{cfgfile} updated"
  File.rename(new_cfgfile, cfgfile)
else
  talk "No changes"
  File.unlink(new_cfgfile)
end
exit