Created
August 7, 2023 05:12
-
-
Save robinkaty/8dd71840aaab40d36468712bad2e7fed to your computer and use it in GitHub Desktop.
Edit Path, show duplicate lines, print clean path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
use Env; | |
use File::Temp qw(tempfile); | |
use File::Basename; | |
sub edit_path_variable { | |
# Get the current PATH variable | |
my $current_path = $ENV{'PATH'} || ''; | |
my @paths_list = split(':', $current_path); | |
# Display the current paths to the user | |
print "Current PATH:\n"; | |
foreach my $idx (1 .. scalar(@paths_list)) { | |
print "$idx. $paths_list[$idx-1]\n"; | |
} | |
# Prepare the text to be edited with "*" before duplicate paths | |
my %seen; | |
my @edited_paths = map { my $count = ++$seen{$_}; ($count > 1 ? '*' : '') . $_ } @paths_list; | |
my $edited_text = join("\n", @edited_paths); | |
# Create a temporary file and write the paths into it | |
my ($temp_fh, $temp_filename) = tempfile(); | |
print $temp_fh $edited_text; | |
close $temp_fh; | |
# Open the temporary file with the default text editor | |
my $editor = $ENV{'EDITOR'} || 'vi'; | |
system("$editor $temp_filename"); | |
# Read the edited paths from the temporary file | |
open my $edited_fh, '<', $temp_filename or die "Error opening temporary file: $!"; | |
@edited_paths = <$edited_fh>; | |
close $edited_fh; | |
# Remove "*" prefix before saving the edited paths | |
my @updated_paths = map { s/^\*//; $_ } @edited_paths; | |
# Join the edited paths back into a new PATH variable | |
my $new_path = join(':', @updated_paths); | |
$new_path =~ s/\R//g; | |
# Update the PATH environment variable | |
$ENV{'PATH'} = $new_path; | |
# Display the updated PATH with "*" for duplicates | |
print "\nUpdated PATH Segments:\n"; | |
foreach my $idx (1 .. scalar(@updated_paths)) { | |
print "$idx. $updated_paths[$idx-1]"; | |
} | |
print "\n\nYou may copy/paste the following to update the current path.\n"; | |
printf ("\nexport PATH=\"%s\"\n",$new_path); | |
# Clean up the temporary file | |
unlink $temp_filename or warn "Error deleting temporary file: $!"; | |
} | |
edit_path_variable(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment