Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over two lists in parallel in /bin/sh

Tags:

shell

sh

I have two lists of equal length, with no spaces in the individual items:

list1="a b c"
list2="1 2 3"

I want to iterate over these two lists in parallel, pairing a with 1, b with 2, etc.:

a 1
b 2
c 3

I'm attempting to support modern portable Bourne shell, so Bash/ksh arrays aren't available. Shelling out to awk would be acceptable in a pinch, but I'd rather keep this in pure sh if possible.

Thank you for any pointers you can provide!

like image 211
emk Avatar asked Feb 13 '09 17:02

emk


1 Answers

This should be a fairly clean solution, but unless you use bash's process substition, it requires the use of temporary files. I don't know if that's better or worse than invoking cut and sed over every iteration.

#!/bin/sh

list1="1 2 3"
list2="a b c"
echo $list1 | sed 's/ /\n/g' > /tmp/a.$$
echo $list2 | sed 's/ /\n/g' > /tmp/b.$$

paste /tmp/a.$$ /tmp/b.$$ | while read item1 item2; do
    echo $item1 - $item2
done

rm /tmp/a.$$
rm /tmp/b.$$
like image 183
Josh Kelley Avatar answered Sep 18 '22 13:09

Josh Kelley