Shabeeralimsn
Shabeeralimsn

Reputation: 825

How to replace a String in a file with another string which contains single quotes using perl script

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";

}

Upvotes: 0

Views: 70

Answers (2)

ernix
ernix

Reputation: 3643

I think this is a typical example of using awk

% <config.cfg awk -v q=\' '$1 == "inputDir" { $2 = q "/home/user/pricing/inflow/" q } { print; }'
monitorinput   'false'
inputDir '/home/user/pricing/inflow/'
useSsl 'false'
enableSorting  'false'
inputtimeunit  'Day'

Upvotes: 0

Shawn
Shawn

Reputation: 52344

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;
}

Upvotes: 3

Related Questions