Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tokenize $PATH by using awk?

Tags:

bash

awk

How can I tokenize $PATH by using awk?

I tried 3 hours, but it totally screwed out.

#!/bin/bash

i=1

while true; do
  token=$($echo $PATH | awk -F ':' '{print $"$i"}')

  if [ -z "$token" ]; then
    break
  fi  

  ((i++))

  if [ -a "$TOKEN/$1" ]; then
    echo "$TOKEN/$1"
    break
  fi  

  break
done

When I run this code, I got

/home/$USERID/bin/ff: line 6: /home/$USERID/bin:/usr/local/symlinks:/usr/local/scripts:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/$USERID/bin: No such file or directory

How can I change my program?

like image 1000
lymose Avatar asked Aug 25 '26 20:08

lymose


2 Answers

What are you trying to do?

This will let you iterate against the individual paths:

echo $PATH | tr ':' '\n' | while read line; do echo $line; done

As @SiegeX notes, an even shorter version works

echo $PATH | while read -d ':' line; do echo $line; done
like image 191
harpo Avatar answered Aug 28 '26 13:08

harpo


Do the whole thing in awk

#!/bin/bash

awk -v addPath="$1" 'BEGIN{RS=":";ORS=addPath "\n"}{$1=$1}1' <<< $PATH

Proof of Concept

$ addPath="/foo"
$ awk -v addPath="$addPath" 'BEGIN{RS=":";ORS=addPath "\n"}{$1=$1}1' <<< $PATH
/usr/local/bin/foo
/usr/bin/foo
/bin/foo
/usr/games/foo
/usr/lib/java/bin/foo
/usr/lib/qt/bin/foo
/usr/share/texmf/bin/foo
./foo
/sbin/foo
/usr/sbin/foo
/usr/local/sbin/foo
like image 29
SiegeX Avatar answered Aug 28 '26 13:08

SiegeX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!