Link to home
Start Free TrialLog in
Avatar of hank1
hank1

asked on

split into an array?, ksh, awk version

How do you split a ksh shell variable into an array with awk?  

Perl version would be
@a = split /:/, $ENV{'PATH'}.

Thanks
Avatar of bpmurray
bpmurray
Flag of Ireland image

This should do it:

{
      path = ENVIRON["PATH"];
      cnt = split(path, dir, ":");

      for (i=0; i<cnt; i++)
            print dir[i];
}
Avatar of hank1
hank1

ASKER

I know this is wrong, but I want the array outside of awk.  Is the awk
struct even close?  :-)
Thanks  (I couldn't get your script to run since I don't know, really
don't know, awk.  I guessed at an invoke of just awk .... no.)



awk {
   path = ENVIRON["PATH"];
   cnt = split(path, dir, ":");
}

while [ ${cnt[index]} ] ; do
  echo Here's the element ${cnt[index]}
  index=$((index + 1))
}
Avatar of hank1

ASKER

Here's something I found, but it uses a file.  Tried your ENVIRON["PATH"] but didn't
go.  Wanted a file



Fiddling with IFS should have helped, though you also want to
double-quote the @ expansion in the for loop's control section:
  oIFS=$IFS
  IFS=${IFS#??}
  set -A array $(awk -F: '{print $3}' go.dat)
  IFS=$oIFS
  for job in "${array[@]}"; do
     echo "$job"
  done

It really depends on what you want to do with the array. Do you simply want to populate a shell array with the contents of PATH? In any case, to run awk the usual way is: awk -f scriptfile [datafile]
I think it's easier to do it in the shell directly. From your use of set -A, I presume you're using ksh, so you can use:

#!/bin/ksh
# Set directory names into "dirs", but set spaces to "+" first
set -A dirs `echo $PATH | tr " " "+" | tr ":" " "`
i=0
while [ ! -z "${dirs[$i]}" ]
do
        # change the "+" to spaces
      dir=`echo ${dirs[$i]} | tr "+" " "`
      echo $dir
      i=`expr $i + 1`
done
what's wrong with:
   set -A dirs `echo "$PATH"|tr ':' ' '`
# assuming that there is space in the path anywhere, which is unusal in Unix anyway
There are spaces in the path - that's the problem. As you've noted, it's easy with no spaces :-)
hmm, who said that there are spaces?
ASKER CERTIFIED SOLUTION
Avatar of ahoffmann
ahoffmann
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hank1

ASKER

Yep, works like a champ.  I'll have to dip into this awk some day.  Thanks.
Avatar of hank1

ASKER

strings windup with enclosed with 's.