从BASH中的另一个文件中的字符串替换一个文件中的字符串

时间:2018-11-08 04:02:08

标签: linux bash shell

我有config_file.txt具有下一个结构

host ='myserver'
login = 'vasya'
password = 'pupkin'

和code.scala具有下一个结构

var_host = '***HOST***'
var_login = '***LOGIN***'
var_password = '***PASS***'

两个文件都在同一目录中。 我需要在配置文件中使用适当的行,并在代码文件中将其替换为适当的行 我在看grep函数,但没有。知道我是否有办法做我需要的事情,或者是否有其他功能可以用来完成这项工作?

谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个快速的小Perl脚本来完成它:

#!/usr/bin/perl -pi
use warnings;
use strict;
use Getopt::Long;

our %vars;

BEGIN {
  my $config_file = "config_file.txt";
  GetOptions("config=s" => \$config_file) or die "Invalid argument\n";
  open my $config, "<", $config_file or die "Unable to open $config_file\n";
  while (<$config>) {
    if (/^(\w+)\s*=\s*('.*')/) {
      $vars{$1} = $2;
    }
  }
  close $config;
}

if (/^var_(\w+)\s*=/) {
  $_ = "var_$1 = $vars{$1}\n" if exists $vars{$1}
}

像这样运行:

$ perl set_vars.pl code.scala

并使用

将配置文件的名称设置为“ config_file.txt”以外的名称
$ perl set_vars.pl --config=foo.txt code.scala
相关问题