views:

56

answers:

3

Hi All,

What would be the best approach to process a call like this to my shell script?

./cars Mazda Toyota 2010 Honda BMW VW 2009

So that it prints out:

Mazda 2010

Toyota 2010

Honda 2009

BMW 2009

VW 2009

I can't use arrays because it's the most simple version of shell so it doesn't support them. Any ideas?

+1  A: 
#!/bin/sh

CARS=

while [ $# -gt 0 ]; do
    # Cheesy way to test if $1 is a year.
    if [ "$1" -gt 0 ] 2> /dev/null; then
        YEAR=$1

        for CAR in $CARS; do
            echo $CAR $YEAR
        done

        CARS=
    else
        # Add car to list
        CARS="$CARS $1"
    fi

    # Process the next command-line argument.
    shift
done
John Kugelman
Nice answer. Clear and easy to read.
hlovdal
A: 
#!/bin/sh
for i in "$@"; do
    case x"$i" in x[0-9]*)
        for j in $justCars; do
            echo $j $i
        done
        justCars=
        continue
        ;;
    esac
    justCars="$justCars $i"
done
DigitalRoss
A: 

you can use gawk for arrays

args="$@"
echo $args | tr " " "\n" | awk 'BEGIN{d=1}
/^[0-9]+/{  
  for(i=1;i<=e;i++){  print a[i],$0  }
  delete a
  e=0
}
!/^[0-9]+/{  a[++e]=$0}'

output

# ./shell.sh  Mazda Toyota 2010 Honda BMW VW 2009
Mazda 2010
Toyota 2010
Honda 2009
BMW 2009
VW 2009
ghostdog74