[英]How do I insert a line above specific lines in a file using Vim or Perl?
[英]How to match above and below lines, then insert words in between them by using Perl?
如何同時匹配特殊字符和多行? 然后在這些匹配的行之間插入文本。 我想匹配行-樣本(“ xx”),direction:north和market_fall(“ when_promotion_8X10_b05afn10ld0b0”){如下所示。 然后在行顏色代碼之后打印文本:0.000;。 我的編碼在某處似乎是錯誤的。 誰能提供指導? 謝謝..
Sample ("apple") {
direction : north ;
I dont want this line+: ;
I dont want this line^ ;
No this line : line ;
color code: 0.000;
I dont want this line: (c*b)+(c*a)+(b*a))" ;
max_price : 3.6;
min_price : 1.2;
I dont want this line_time() {
I dont want this line_t_sense : positive_1 ;
No_this line either : "c" ;
market_fall ("when_promotion_8X10_b05afn10ld0b0") {
我的編碼:
if(my $line =~ m/Sample(" ")/ & /direction : north/ & /market_fall ("when_promotion_8X10_b05afn10ld0b0") {/ ){ #match specific line
print "aa\n"; #print words at previous line
}
}
嘗試從shell跟隨perl
一線
perl -0777 -pe 's/(Sample\s*\("[^"]+"\)\s*\{.*direction\s*:\s*\w+\s*;.*color\s*code:\s*0.000;)(.*market_fall\s*\("[^"]+"\))/$1\nLineYouWantToInsert$2/gs' file
編輯
如果必須在perl script
使用它,請嘗試以下代碼。
#!/usr/bin/perl
use strict;
use warnings;
open my $fh, '<', 'file' or die $!;
my $line = do { local $/; <$fh> };
$line =~ s/(Sample\s*\("[^"]+"\)\s*\{.*direction\s*:\s*\w+\s*;.*color\s*code:\s*0.000;)(.*market_fall\s*\("[^"]+"\))/$1\nLineYouWantToInsert$2/gs;
print $line;
close $fh
我喜歡阿比蘇的建議。 這是一些示例代碼:
#!/usr/bin/perl
my $l1;
my $l2;
while( my $line = <> ){
$l1 = $l2;
$l2 = $line;
if( $l1 =~ /start1/ && $l2 =~ /start2/ ){
print $l1;
print "Inserted Text\n";
print $l2;
}
else {
print $l2;
}
}
給定輸入:
a
b
c
start1
start2
d
e
你會得到:
a
b
c
start1
start1
Inserted Text
start2
d
e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.