bash shell how to print line in file including pattern taken from user searching with data type for pattern -
i want take pattern user , print line includes (the whole record) in terminal searching process data types id integer (pk
) , name string , salary integer
more explanation: if searching pattern 2
, id have display id , not salary contains 2000 , that's problem... didn't face problem string names in id , salary.
the code incorrectly formatted.
#! /bin/bash #################taking tablename "database name"############### echo "enter table name"; read tablename; if [ -f ./tables/$tablename ]; #############check table exists###################### echo "file $tablename exists." echo "1)search id"; echo "2)search name"; echo "3)search salary"; echo "enter choice"; read input echo "enter pattern"; read pattern; if [ $input -eq 1 ] test= cut -d ',' -f1 ./tables/$tablename if [[ ${#test[$pattern]} ]]; ###############problem here################ fi elif [ $input -eq 2 ] grep $pattern ./tables/$tablename elif [ $input -eq 3 ] ##########################problem here###################### else echo "error in input"; fi else echo "table $tablename not exist " fi ##########################code ends#################
and file has records:
id:pk,name:str,salary:int, 2,tony,2000, 3,tony,2000, 4,sara,3000,
you use case different operations depending of input choice. , in cases, values file.
echo "enter table name"; read tablename; if [ ! -f ./tables/$tablename ]; #try avoid looooong if/then blocks if can handle error right away echo "table $tablename not exist" exit 1 fi #############check table exists###################### echo "file $tablename exists." echo "1)search id"; echo "2)search name"; echo "3)search salary"; echo "enter choice"; read input echo "enter pattern"; read pattern; entries=() #initialize entries empty array case $input in 1) #case id entries=($(grep -p "^${pattern}," "./tables/$tablename")) ;; 2) #case name entries=($(grep -p "^\d*,${pattern}," "./tables/$tablename")) ;; 3) #case salary entries=($(grep -p ",${pattern}$" "./tables/$tablename")) ;; *) #choice not found echo "error in input" esac if [[ "${#entries[@]}" = "0" ]]; #entries array count 0 echo "no entries found matching pattern" exit 1 fi #to noted here, entries useless if want print match #(use grep directly , print output). #thank's jonathan leffler trick allowing print whole array in 1 line printf "%s\n" "${entries[@]}"
Comments
Post a Comment