Parsing and Printing $ PATH Using Unix

I put PATH in a text file and would like to print each path on a new line using a simple command on UNIX.

I found a long way to do it like this ...

cat Path.txt | awk -F\; '{print $1"\n", $2"\n", ... }' 

This, however, seems inefficient, so I know there should be a way to quickly print my results in new lines every time without having to manually call each field separated by a separator.

+7
source share
6 answers

Another way:

 echo $PATH | tr : '\n' 

or

 tr : '\n' <Path.txt 
+16
source

The tr solution is correct, but if you are going to use awk then there is no need for a loop:

 $ echo "$PATH" /usr/local/bin:/usr/bin:/cygdrive/c/winnt/system32:/cygdrive/c/winnt $ echo "$PATH" | awk -F: -v OFS="\n" '$1=$1' /usr/local/bin /usr/bin /cygdrive/c/winnt/system32 /cygdrive/c/winnt 
+2
source

With Perl for UNIX / UNIX-like:

 echo $PATH | perl -F: -ane '{print join "\n", @F}' 

With any operating systems (tested on Windows XP, Linux, Minix, Solaris):

 my $sep; my $path; if ($^O =~ /^MS/) { $sep = ";"; $path = "Path"; } else { $sep = ":"; $path = "PATH"; } print join "\n", split $sep, $ENV{$path} . "\n"; 

If you are using for Unix, try the following code:

 printf '%s\n' ${PATH//:/ } 

This is the use of the bash parameter extension

0
source

I have a Perl script that I use for this:

 #!/usr/bin/env perl # # "@(#)$Id: echopath.pl,v 1.8 2011/08/22 22:15:53 jleffler Exp $" # # Print the components of a PATH variable one per line. # If there are no colons in the arguments, assume that they are # the names of environment variables. use strict; use warnings; @ARGV = $ENV{PATH} unless @ARGV; foreach my $arg (@ARGV) { my $var = $arg; $var = $ENV{$arg} if $arg =~ /^[A-Za-z_][A-Za-z_0-9]*$/; $var = $arg unless $var; my @lst = split /:/, $var; foreach my $val (@lst) { print "$val\n"; } } 

I call it like this:

 echopath $PATH echopath PATH echopath LD_LIBRARY_PATH echopath CDPATH echopath MANPATH echopath $CLASSPATH 

etc .. You can specify a variable name or a variable value; he works both ways.

0
source

AWK:

 echo $PATH|awk -F: '{gsub(/:/,"\n");print}' 

Perl:

 echo $PATH|perl -F: -lane 'foreach(@F){print $_}' 
0
source

for AWK, in addition to:

 echo $PATH | awk -vFS=':' -vOFS='\n' '$1=$1' 

You can:

 echo $PATH | awk -vRS=':' '1' 
0
source

All Articles