0

I am trying to merge two very different scripts together for consolidation and ease of use purposes. I have an idea of how I want these scripts to look and operate, but I could use some help getting started. Here is the flow and look of the script:

The input file would be a standard text file with this syntax:

#Vegetables
Broccoli|Green|14
Carrot|Orange|9
Tomato|Red|7

#Fruits
Apple|Red|15
Banana|Yellow|5
Grape|Purple|10

The script would take the input of this file. It would ignore the commented portions, but use them to dictate the output. So based on the fact that it is a Vegetable, it would perform a specific function with the values listed between the delimiter (|). Then it would go to the Fruits and do something different with the values, based on that delimiter. Perhaps, I would add Vegetable/Fruit to one of the values and dependent on that value it would perform the function while in this loop to read the file. Thank you for your help in getting this started.

UPDATE: So I am trying to implement the IFS setup and thought of a more logical arrangement. The input file will have the "categories" displayed within the parameters. So the setup will be like this:

Vegetable|Carrot|Yellow
Fruit|Apple|Red
Vegetable|Tomato|Red

From there, the script will read in the lines and perform the function. So basically this type of setup in shell:

while read -r category item color
do
    if [[ $category == "Vegetable" ]] ; then
        echo "The $item is $color"
    elif [[ $category == "Fruit" ]] ; then
        echo "The $item is $color"
    else
        echo "Bad input"
 done < "$input_file"

Something along those lines...I am just having trouble putting it all together.

4

2 回答 2

0

使用 read 输入行。对它们的前缀做一个 case 语句:

{
  while read DATA; do
    case "$DATA" in
       \#*) ... switch function ...;;
         *) eval "$FUNCTION";;
    esac
  done
} <inputfile

根据您的问题,您可能希望在读取和读取多个变量之前尝试设置 $IFS 1 go。

于 2013-08-09T09:55:17.613 回答
0

每次遇到#指令都可以重新定义处理函数:

#! /bin/bash
while read line ; do
    if [[ $line == '#Vegetables' ]] ; then
        process () {
            echo Vegetables: "$@"
        }
    elif [[ $line == '#Fruits' ]] ; then
        process () {
            echo Fruits: "$@"
        }
    else
        process $line
    fi
done < "$1"

请注意,该脚本不会跳过空行。

于 2013-08-09T10:25:53.110 回答