Skip to content

Instantly share code, notes, and snippets.

@Osse
Created June 10, 2012 14:42
Show Gist options
  • Save Osse/2905989 to your computer and use it in GitHub Desktop.
Save Osse/2905989 to your computer and use it in GitHub Desktop.
Path shortener
#!/usr/bin/env perl
use strict;
use warnings;
my $cwd = $ENV{'PWD'};
my $home = $ENV{'HOME'};
if ($cwd eq $home) {
print '~'; exit;
}
elsif ( $cwd eq '/') {
print '/'; exit;
}
my $product; # What will be written out
my $start; # At what level we beging shortening
if (index($cwd, $home) != -1 ) {
$product = '~/'; $start = 3;
}
else {
$product = '/'; $start = 1;
}
my @dirs = split('/', $cwd);
my $curpath = $product; # $curpath is where the script is current at
my $length;
my $temp;
my @files;
for (my $i = $start; $i < scalar(@dirs)-1; $i++) {
$length = 0;
do {
$length++;
$temp = substr $dirs[$i], 0, $length; # Substring av dirname
@files = glob $curpath.$temp."*";
} while (scalar(@files) > 1 && $length < length($dirs[$i]));
$product .= $temp.'/'; # After the loop is done $temp is sufficiently shortened
$curpath .= $dirs[$i].'/'; # Change curpath to be the next step in the path
}
print $product.$dirs[-1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment