bash shell如何打印文件中的行,包括从用户搜索的模式中获取的模式数据类型

时间:2014-04-15 02:38:51

标签: bash shell

我想从用户和打印行获取模式,它在终端中包含(整个记录)它的搜索过程,但数据类型为id整数(pk)和名称字符串和工资整数

更多解释:如果我使用模式2进行搜索并且其ID必须仅显示id而不是工资包含2000而且问题是......我没有面对字符串名称存在这个问题,但是它的ID和工资。

代码格式不正确。

#! /bin/bash
    #################taking tablename "database name"###############
        echo "enter table name";
        read tableName;
        if [ -f ./tables/$tableName ];
        then
    #############check table exists######################
        echo "File $tableName exists."
        echo "1)search with the id";
        echo "2)search with the name";
        echo "3)search with the salary";
        echo "enter your choice";
        read input
        echo "enter your pattern";
        read pattern;
                if [ $input -eq 1 ] 
                then 
                            test=  cut -d ',' -f1 ./tables/$tableName
                        if [[ ${#test[$pattern]} ]];
                        then
                        ###############problem here################ 
                        fi
                elif [ $input -eq 2 ]
                then 
                grep $pattern ./tables/$tableName
                elif [ $input -eq 3 ]
                then 
                ##########################problem here######################
                else 
                echo "error in input";
                fi
        else
            echo "table $tableName does not exist "
        fi
    ##########################code ends#################

该文件有以下记录:

id:pk,name:str,salary:int,
2,tony,2000,
3,tony,2000,
4,sara,3000,

1 个答案:

答案 0 :(得分:1)

您可以根据输入选择使用案例执行不同的操作。在这些情况下,从文件中获取值。

echo "enter table name";
read tableName;
if [ ! -f ./tables/$tableName ]; then   #Try to avoid looooong if/then blocks if you can handle the error right away
   echo "table $tableName does not exist"
   exit 1
fi
#############check table exists######################
    echo "File $tableName exists."
    echo "1)search with the id";
    echo "2)search with the name";
    echo "3)search with the salary";
    echo "enter your choice";
    read input
    echo "enter your pattern";
    read pattern;
entries=()        #Initialize entries with an empty array
case $input in 
    1) #case by id
       entries=($(grep -P "^${pattern}," "./tables/$tableName"))
       ;;
    2) #case by name
       entries=($(grep -P "^\d*,${pattern}," "./tables/$tableName"))
       ;;
    3) #case by salary
       entries=($(grep -P ",${pattern}$" "./tables/$tableName"))
       ;;
    *) #choice not found
       echo "error in input"
esac

if [[ "${#entries[@]}" = "0" ]]; then #entries array count is 0
   echo "No entries found matching your pattern"
   exit 1
fi

#To be noted that here, entries is useless if you just want to print the match
#(use grep directly and it will print the output).   

#Thank's to Jonathan Leffler for this trick allowing to print a whole array in one line
printf "%s\n" "${entries[@]}"