在我的文件中,我有像
这样的行String sql="select * from "+
"emp_data";
我想替换它像
String sql = Query1;
我怎样才能使用perl
我正在使用
$curUrl ="select * from emp_data" ;
$curUrl = quotemeta $curUrl;
$newVariable = "Query1";
$data =~ s/$curUrl/$newVariable/g;
这是为单线工作。不是为了破碎的
答案 0 :(得分:0)
尝试进行两次替换。
$curUrl ="select * from emp_data" ;
$curUrl = quotemeta $curUrl;
$newVariable = "Query1";
$data = 'String sql="select * from "+
"emp_data";';
$data=~s/"|\+|\n\s+//g; # Here i replace the " + and \n\s character with empty.
$data =~s/$curUrl/$newVariable/g;
print $data;
答案 1 :(得分:0)
您可以考虑使用此经过测试的sed
脚本:
sed -n '
:1
/^.*[+][ ]*$/ {
h;
:2
n; H; /^.*[+][ ]*$/ {
b2
}
x
s/[+\n\t\r]//g
s/["][[:space:][:blank:]]*["]//g
s/["][[:space:][:blank:]]*select [*] from emp_data[[:space:][:blank:]]*["]/Query1/
p; x;
b1;
}'
测试:
sed -n '
:1
/^.*[+][ ]*$/ {
h;
:2
n; H; /^.*[+][ ]*$/ {
b2
}
x
s/[+\n\t\r]//g
s/["][[:space:][:blank:]]*["]//g
s/["][[:space:][:blank:]]*select [*] from emp_data[[:space:][:blank:]]*["]/Query1/
p; x;
b1;
}' myfile.txt
String sql=Query1;
答案 2 :(得分:0)
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
# Here, the variables $/, $^I, and @ARGV either have their default values
# or some other values that were set by code appearing here.
{
local $/ = ";"; #local => temporarily change the value of this variable until the closing parenthesis of this block is encountered
local $^I = ".bak";
local @ARGV = 'data.txt';
while (<>) {
my $perl_statement = $_;
$perl_statement =~ s/sql = .*/sql = Query1/xms ;
print $perl_statement; #This is redirected into the file.
}
} #Automatically restores the previous values for $/, $^I, and @ARGV.
$/
=&gt;输入行分隔符(默认=&gt;“\ n”)。使<$INFILE>
读取并包括指定为一行的字符$^I
=&gt;如果设置为字符串(默认=&gt; undef),则使菱形运算符神奇,这样您就可以在某处编辑文件。任何打印语句都将写入新文件,其名称将与原始文件相同。如果您编写$^I = ".bak"
,则原始文件将存储在原始文件名加“.bak”扩展名的文件中。空白字符串表示没有备份@ARGV
=&gt;钻石操作员从该数组中的文件中读取。
示例运行:
~/pperl_programs$ cat data.txt
String sql="select * from "+
"emp_data";
hello word="select * from "+
"emp_data";
~/pperl_programs$ perl 1.pl
~/pperl_programs$ cat data.txt
String sql = Query1
hello word="select * from "+
"emp_data";
或者,也许您想要替换所有出现的模式:
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
my $pattern = q{"select * from "+
"emp_data"};
{
local $/ = ";";
local $^I = "";
local @ARGV = 'data.txt';
while (<>) {
my $perl_statement = $_;
$perl_statement =~ s/= \Q$pattern/ = Query1/xms;
print $perl_statement;
}
}
示例运行:
~/pperl_programs$ cat data.txt
String sql="select * from "+
"emp_data";
hello word="select * from "+
"emp_data";
~/pperl_programs$ perl 1.pl
~/pperl_programs$ cat data.txt
String sql = Query1;
hello word = Query1;