使用for循环删除最后一个字符

人气:162 发布:2023-01-03 标签: scripting unix for-loop trim

问题描述

我有一个输入需要查询,但如果查询返回NULL,则应该删除输入中的最后一个字符,然后将再次使用它进行查询,直到从表读取值。

输入:123456

查询:select col1 from table where input='123456';--空输出

输入:12345

查询:select col1 from table where input='12345';--空输出

输入:1234

查询:select col1 from table where input='1234';--空输出

输入:123

查询:select col1 from table where input='123';--空输出

输入:12

查询:select col1 from table where input='12';--非空输出

返回输出:col1 value

method () {
export input=$1
echo "input : "$input

for (i++, input.length(), i++ ){ #for entire length of input
   methodForQuery "$input" #deduct last character for every iteration
   echo "output : "$output   
   
   if [ -z "$output" ]
   then
      continue #if output is null, deduct last character
               #but if last one character still returns null, set output as null
   else
      break #if output is not null, break loop and return $output
   fi
}

echo "output : " $output
}

methodForQuery (){
   output=#sqlplus... 
   select col1 from table where input='$input' and rownum < 2;
}

推荐答案

使用ff:

method () {
export input=$1
echo "input : "$input
j="$input"

for (( i=1, j=0 ; i<=$length ; i++, j=j+1)); do
   len=$(echo "$((length-$j))")
   newinp=$(echo ${input:0:$len})
   methodForQuery "$newinp"
   echo "output : "$output  
   
   if [ -z "$output" ]
   then
      continue 
   else
      break 
   fi
}

echo "output : " $output
}

methodForQuery (){
   output=#sqlplus... 
   select col1 from table where input='$input' and rownum < 2;
}

25