How to iterate through a comma-separated list and execute a command for each entry

csvkshscripting

I have been give a command which outputs a comma-separated list for autosys jobs in the variable $all_jobs:

box=box-of-jobs;all_jobs=$(jobscout -box $box | egrep "^\w+" | tr '\n' ','  | sed s/.$//); 

I want to call a sendevent command for each item in the list:

sendevent -verbose -S NYT -E JOB_OFF_HOLD -J $job --owner me

So for example if $all_jobs evaluated job1,job2,job3

I want to call

sendevent -verbose -S NYT -E JOB_OFF_HOLD -J job3 --owner me
sendevent -verbose -S NYT -E JOB_OFF_HOLD -J job2 --owner me
sendevent -verbose -S NYT -E JOB_OFF_HOLD -J job1 --owner me

I'm sure I could write a ksh script to loop through, but I know these things can often be written much faster using awk/sed, both of which I'm not very familiar with so it's beyond my megre skills. I'm using ksh (rather than bsh).

Best Answer

If you're sure that the fields between the commas do not contain any whitespaces than you could do something like this:

for job in $(echo $all_jobs | tr "," " "); do
    sendevent -verbose -S NYT -E JOB_OFF_HOLD -J "$job" --owner me
done

If you need something more robust, take a look at the tools needed to deal with CSV files under Unix.

Related Question