如何使用perl提取特定字符串



我在一个文件文件中有一组字符串,比如"-f/path/filename1.f"、"-f$path/filename2.f"等。f我想读取文件.f并在另一个文件中提取/path/filenname1.f、$path/filenname2.f等。我试着在网上找到解决方案,但看起来一团糟。

对于这种简单的模式搜索,有什么干净简单的解决方案吗?

以下是要求示例,

file.f (input file to perl script)
-f /path/filename1.f
-f $path1/filename2.f
-f /path/filename3.f
-f $path2/filename4.f
outputfile.f
/path/filename1.f
$path1/filename2.f
/path/filename3.f
$path2/filename4.f

基本上,我只想要文件.f的路径字符串

一些perl代码可以解决您的问题:

use strict;
use warnings;
open my $fhi, "<", "file.f" or die "Error: $!";
open my $fho, ">", "output.f" or die "Error: $!";
while( <$fhi> ) {  # Read each line in $_ variable
s/^-f //;      # Remove "-f " at the beginning of $_ 
print $fho $_; # print $_ to output.f file
}
close $fhi;
close $fho;

最简单的方法是使用cut:

cut -f2 -d’ ‘ input_file > output_file

或者您可以使用Perl:

perl -lane ‘print $F[1]’ input_file > output_file

这些解决方案提取输入的第二个字段并打印出来

查看以下解决方案-

在这里,-f之后的所有内容都将被取出。

#!/usr/bin/perl
use strict;
use warnings;
open(FILE,"<file.f"); 
while(<FILE>) 
print "$1n" if($_ =~ /^-fs(.*)/);
}

最新更新