windows - Search for specific lines from a file -


i have array contains data text file.

i want filter array , copy information array. grep seems not work.

here's have

$file = 'files.txt';  open (fh, "< $file") or die "can't open $file read: $!"; @lines = <fh>; close fh or die "cannot close $file: $!";  chomp(@lines);  foreach $y (@lines){      if ( $y =~ /(?:[^\\]*\\|^)[^\\]*$/g ) {         print $1, pos $y, "\n";     } } 

files.txt

public_html trainings , events general office\resources general office\travel general office\office opperations\contacts general office\office opperations\coordinator operations public_html\accordion\dependencies\.svn\tmp\prop-base public_html\accordion\dependencies\.svn\tmp\props public_html\accordion\dependencies\.svn\tmp\text-base 

the regular expression should take last 1 or 2 folders , put them own array printing.

a regex can picky this. far easier split path components , count off many need. , there tool fits exact purpose, core module file::spec, mentioned xxfelixxx in comment.

you can use splitdir break path, , catdir compose one.

use warnings 'all'; use strict; use feature 'say';  use file::spec::functions qw(splitdir catdir);  $file = 'files.txt';     open $fh, '<', $file or die "can't open $file: $!";  @dirs;     while (<$fh>) {     next if /^\s*$/;  # skip empty lines     chomp;      @all_dir = splitdir $_;      push @dirs, (@all_dir >= 2 ? catdir @all_dir[-2,-1] : @all_dir); } close $fh;  @dirs; 

i use module's functional interface while heavier work want object oriented one. reading whole file array has uses in general process line line. list manipulations can done more elegantly went simplicity.

i'd add few general comments

  • always start programs use strict , use warnings

  • use lexical filehandles, my $fh instead of fh

  • being aware of (at least) dozen-or-two of used modules really helpful. example, in above code never had mention separator \.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -