Alex Rivera | Logout

Iterating over two lists in parallel in /bin/sh

Asked 2009-02-13T17:17:07.887
12

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!

Edit
Report

1 Answer

1

Solution not using arrays:

list1="aaa1 aaa2 aaa3"
list2="bbb1 bbb2 bbb3"

tmpfile1=$( mktemp /tmp/list.XXXXXXXXXX ) || exit 1
tmpfile2=$( mktemp /tmp/list.XXXXXXXXXX ) || exit 1

echo $list1 | tr ' ' '\n'  > $tmpfile1
echo $list2 | tr ' ' '\n'  > $tmpfile2

paste  $tmpfile1  $tmpfile2

rm --force $tmpfile1  $tmpfile2
answered 2009-02-13T18:28:37.947

Your Answer