【问题标题】:Remove last character using for loop使用 for 循环删除最后一个字符
【发布时间】:2021-12-13 12:34:39
【问题描述】:

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

输入:123456

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

输入:12345

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

输入:1234

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

输入:123

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

输入:12

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

返回输出: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;
}

【问题讨论】:

  • 你不需要循环; ${input%?} 返回 $input 的值,去掉最后一个字符。

标签: for-loop unix scripting trim


【解决方案1】:

使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多