find and Replace String in Perl - Regexp

Trying to find and replace one string with another string in a file

#!/usr/bin/perl

	$csd_table_path = "/file.ntab";
	$find_str = '--bundle_type=021';
	$repl_str = '--bundle_type=021 --target=/dev/disk1s2';
	if( system("/usr/bin/perl -p -i -e 's/$find_str/$repl_str/' $csd_table_path") != 0 ) {
		print "\n\n\nERROR: adding new target to <$csd_table_path>!\n\n\n";
		exit 1;
	}
	print "Msg: file modified \n";

exit 0;

however getting errors ...

Bareword found where operator expected at -e line 1, near "--target"
(Missing operator before target?)
Unknown regexp modifier "/v" at -e line 1, at end of line
syntax error at -e line 1, near "--target"
Execution of -e aborted due to compilation errors.

$repl_str contains a / that is also used as a separator.
Take another separator
's#$find_str#$repl_str#'
--
Why do you run another perl instance?

1 Like

Another option is to escape the ` / '

$repl_str = '--bundle_type=021 --target=\/dev\/disk1s2';
#!/usr/bin/perl
.
.
.
if( system("/usr/bin/perl -p -i -e 's/$find_str/$repl_str/' $csd_table_path") != 0 ) {
		print "\n\n\nERROR: adding new target to <$csd_table_path>!\n\n\n";
		exit 1;
	}
.
.
.

Running Perl inside Perl by invoking a system call is like running a virtual machine inside a virtual machine, to list the content of a file system. By the way, I do not believe it does what you think it does, neither.

1 Like