如何在unix shell中处理这样的内容?

时间:2009-11-28 21:26:36

标签: shell unix

将这样的调用处理到我的shell脚本的最佳方法是什么?

./cars Mazda Toyota 2010 Honda BMW VW 2009

打印出来:

Mazda 2010

丰田2010

本田2009

宝马2009

大众汽车2009

我不能使用数组,因为它是最简单的shell版本,所以它不支持它们。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

#!/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

答案 1 :(得分:0)

#!/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

答案 2 :(得分:0)

你可以使用gawk作为数组

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}'

输出

# ./shell.sh  Mazda Toyota 2010 Honda BMW VW 2009
Mazda 2010
Toyota 2010
Honda 2009
BMW 2009
VW 2009
相关问题