I am looking for every occurence of a search term, e.g. ddd
, in a file and output the surroundings, like this:
我正在查找一个搜索词的每一个出现的情况,例如ddd,在一个文件中并输出环境,如下所示:
File.txt
File.txt
aaa bbb ccc ddd eee fff
ttt uuu iii eee ddd
ddd
ggg jjj kkk ddd lll
output
输出
ccc ddd eee
eee ddd
ddd
kkk ddd lll
As a starting point, I am using this piece of code
作为起点,我正在使用这段代码
#!/usr/bin/perl -w
while(<>) {
while (/ddd(\d{1,3}))/g) {
print "$1\n"
}
}
4 个解决方案
#1
3
You can try the following..it gives the output you want:
你可以试试下面的方法。它给出你想要的输出:
while(<>) {
if(/((?:\w+ )?ddd(?: \w+)?)/) {
print "$1\n";
}
}
Regex used:
正则表达式使用:
( # open the grouping.
(?:\w+ )? # an optional word of at least one char followed by a space.
ddd # 'ddd'
(?: \w+)? # an optional space followed by a word of at least one char.
) # close the grouping.
#2
1
#!/usr/bin/perl -w
while (<>) {
if (/((?:[a-z]{3} )?ddd(?: [a-z]{3})?)/)
print "$1\n";
}
#3
1
while (<>) {
chomp;
my @words = split;
for my $i (0..$#words) {
if ($words[$i] eq 'ddd') {
print join ' ', $i > 0 ? $words[$i-1] : (), $words[$i], $i < $#words ? $words[$i+1] : ();
print "\n";
}
}
}
#4
-1
#!/usr/bin/perl
while (<>) {
chomp;
@F = split /\s+/;
if (/^ddd$/) {print $_."\n";next};
for ($i=0; $i<=$#F;$i++) {
if ($F[$i] eq 'ddd') {
print "$F[$i-1] $F[$i] $F[$i + 1]\n";
}
}
}
#1
3
You can try the following..it gives the output you want:
你可以试试下面的方法。它给出你想要的输出:
while(<>) {
if(/((?:\w+ )?ddd(?: \w+)?)/) {
print "$1\n";
}
}
Regex used:
正则表达式使用:
( # open the grouping.
(?:\w+ )? # an optional word of at least one char followed by a space.
ddd # 'ddd'
(?: \w+)? # an optional space followed by a word of at least one char.
) # close the grouping.
#2
1
#!/usr/bin/perl -w
while (<>) {
if (/((?:[a-z]{3} )?ddd(?: [a-z]{3})?)/)
print "$1\n";
}
#3
1
while (<>) {
chomp;
my @words = split;
for my $i (0..$#words) {
if ($words[$i] eq 'ddd') {
print join ' ', $i > 0 ? $words[$i-1] : (), $words[$i], $i < $#words ? $words[$i+1] : ();
print "\n";
}
}
}
#4
-1
#!/usr/bin/perl
while (<>) {
chomp;
@F = split /\s+/;
if (/^ddd$/) {print $_."\n";next};
for ($i=0; $i<=$#F;$i++) {
if ($F[$i] eq 'ddd') {
print "$F[$i-1] $F[$i] $F[$i + 1]\n";
}
}
}