I have a text file in UNIX (say config.cfg) which has data like below. Key and value seperated by tab.
monitorinput 'false'
inputDir ''
useSsl 'false'
enableSorting 'false'
inputtimeunit 'Day'
I want to update the value of inputDir using perl or shell script.
before update:
inputDir ''
so after update it should be
inputDir '/home/user/pricing/inflow/'
I tried many things. not able to put value within the quotes.
use File::Basename;
use File::Path;
use File::Copy;
use File::Find;
use File::Path qw(make_path remove_tree);
use Getopt::Std;
my $target_conf_file="/home/pricing/config.cfg";
my $node_backup_dir = "/home/user/pricing/inflow/";
#my $commndresult= system("sed -i 's|^inputDir.*|inputDir\t'${node_backup_dir}'|g' $target_conf_file");
my $commndresult= system("sed -i 's|^inputDir.*|inputDir '$node_backup_dir'|g' $target_conf_file");
if ( $commndresult == 0 )
{
print "\nInput Directory updated";
}
CodePudding user response:
There's really no need to drag sed
into this when you can just use perl
directly. The handy Path::Tiny
module makes it trivial:
#!/usr/bin/env perl
use warnings;
use strict;
use Path::Tiny;
my $target_conf_file="/home/pricing/config.cfg";
my $node_backup_dir = "/home/user/pricing/inflow/";
path($target_conf_file)->edit_lines(sub {
$_ = "inputDir\t'${node_backup_dir}'" if /^inputDir\s/
});
or if you can't install an extra module for some reason, (ab)using the behavior of -i
(Inspired by this answer):
#!/usr/bin/env perl
use warnings;
use strict;
my $target_conf_file="/home/pricing/config.cfg";
my $node_backup_dir = "/home/user/pricing/inflow/";
our $^I = "";
our @ARGV = ($target_conf_file);
while (<ARGV>) {
$_ = "inputDir\t'${node_backup_dir}'" if /^inputDir\s/;
print;
}
CodePudding user response:
Using sed
$ node_backup_dir="/home/user/pricing/inflow/"
$ sed "s~^inputDir[^']*'~&$node_backup_dir~" input_file
monitorinput 'false'
inputDir '/home/user/pricing/inflow/'
useSsl 'false'
enableSorting 'false'
inputtimeunit 'Day'