views:

92

answers:

4

I have a string that has a file path:

$workingFile = '/var/tmp/A/B/filename.log.timestamps.etc';

I want to change the directory path, using two variables to note the old path portion and the new path portion:

$dir = '/var/tmp';
$newDir = '/users/asdf';

I'd like to get the following:

'/users/asdf/A/B/filename.log.timestamps.etc'
+4  A: 

Remove the trailing slash from $newDir and:

($foo = $workingFile) =~ s/^$dir/$newDir/;
sh-beta
Looks good. To be completely safe, you might want to add a beginning of line match just to cover the case when $dir = A/B
Greg Harman
slash removed thanks this is what im after guys
wmitchell
@Greg Harman: good call, added ^ to the beginning
sh-beta
A: 

I've quite recently done this type of thing.

$workingFile = '/var/tmp/A/B/filename.log.timestamps.etc';
$dir         = '/var/tmp';
$newDir      = '/users/asdf';

unless ( index( $workingFile, $dir )) { # i.e. index == 0
    return $newDir . substr( $workingFile, length( $dir ));
}
Axeman
A: 

sh-beta's answer is correct insofar as it answers how to manipulate strings, but in general it's better to use the available libraries to manipulate filenames and paths:

use strict; use warnings;
use File::Spec::Functions qw(catfile splitdir);

my $workingFile = '/var/tmp/A/B/filename.log.timestamps.etc';
my $dir = '/var/tmp';
my $newDir = '/usrs/asdf';

# remove $dir from $workingFile and keep the rest
(my $keepDirs = $workingFile) =~ s#^\Q$dir\E##;

# join the directory and file components together -- splitdir splits
# into path components (removing all slashes); catfile joins them;
# / or \ is used as appropriate for your operating system.
my $newLocation = catfile(splitdir($newDir), splitdir($keepDirs));
print $newLocation;
print "\n";

gives the output:

/usrs/asdf/tmp/filename.log.timestamps.etc

File::Spec is distributed as part of core Perl. Its documentation is available at the command-line with perldoc File::Spec, or on CPAN here.

Ether
+5  A: 

There is more than one way to do it. With the right module, you save a lot of code and make the intent much more clear.

use Path::Class qw(dir file);

my $working_file = file('/var/tmp/A/B/filename.log.timestamps.etc');
my $dir          = dir('/var/tmp');
my $new_dir      = dir('/users/asdf');

$working_file->relative($dir)->absolute($new_dir)->stringify;
# returns /users/asdf/A/B/filename.log.timestamps.etc
daxim
For anything more serious than a one-off script, this is a better answer than mine.
sh-beta