Question

I have a bunch of data that is stored in sub-directories labeled by date. I have used the Cwd command to get the Current working directory so that I can then print it to the vi file that I am writing with the recovered data from the sub-directories. I am using the Cwd as a prefix to the data strings. Is there a way to print only the current directory name and not the path?

example:

Instead of printing-

 /d2/aschwa/archive_data/METAR_data/20120302KDUX 121255Z.........

Is there a way to print only-

 20120302KDUX 121255Z.........

Here's the code I'm using-

use strict;
use warnings;
use file::find;
use Cwd;

my @folder = ("/d2/aschwa/archive_project/METAR_data/");

open( OUT , '>', 'KDUX_METARS.txt') or die "Could not open $!";

print OUT "Station, Day/Time, Obs Type, Wind/Gust, Vis, Sky, T/Td, Alt, Rmk\n";
print STDOUT "Finding METAR files\n";

my $criteria = sub {if(-e && /^2012/) {
                    open(my $file,$_) or die "Could not open $_ $!\n";
                      my $dir = getcwd;
                        while(<$file>) {
                          print OUT $dir,$_ if /KDUX ....55Z|KDUX ....05Z/;
                            }
                         }
                      };
find($criteria, @folder);
close OUT;
Was it helpful?

Solution

In Perl, you can use functions basename or fileparse to extract the file name from a path.

They are included in the core module File::Basename.

OTHER TIPS

Simply split, then pop.

Shamelessly stolen from perlmonks:

$ perl -e 'print pop @{[split m|/|, "/home/bin/scripts/test.pl"]};'
test.pl

Reference link: http://www.perlmonks.org/?node_id=241089

You can combing the perl module File::Basename with Cwd to get the directory without the path

perl -MCwd -MFile::Basename -e 'my $dir = cwd; print basename($dir)'

Why don't you just get the content after the last slash with a regexp like below:

 $path = '/d2/aschwa/archive_data/METAR_data/20120302KDUX 121255Z.........';
 $path = $1 if $path =~ m~/([^/]*)/?$~;

This is in my opinion the best way to do it. The above code is just an example, but the regexp there will do the job you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top