LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   pattern match problem (https://www.linuxquestions.org/questions/programming-9/pattern-match-problem-4175462582/)

ramsavi 05-19-2013 11:21 AM

pattern match problem
 
if i have to do pattern match for file name with digit alphanumeric value like this
Code:

File_1234.csv

File_12sd45rg.csv

i am using this File_[0-9a-zA-Z]*.csv
and File_[0-9]*.csv for digit pattern match.

when i am doing pattern match for the digit then both alphanumeric match
and digit match is coming.
where only digit match should should come.
If usinng [:digit:] then it is not working.

Code:

the part of code which i am using is like this


i=0
len=${#arr[@]}
echo $len

shopt -s extglob

pattern=*[0-9]*.*
pattern1=*[0-9]*_[0-9]*.*
pattern2=*[a-zA-z0-9]*.*
pattern3=File_[0-9]*_[0-9]*.csv
pattern4=File_[a-zA-Z]*_[a-zA-Z]*.csv
pattern5=File_[a-zA-Z0-9]*_[a-zA-Z0-9]*.csv
pattern6=File_[0-9]*[a-zA-Z]*.csv

while [ $len -gt $i ]
do
  case ${arr[$i]} in
  $pattern) echo "pattern %N% match" ;;
  esac
  case ${arr[$i]} in
  $pattern1) echo "pattern %N%_%N% match" ;;
  esac
  case ${arr[$i]} in
  $pattern2) echo "pattern %x% match" ;;
  esac


PTrenholme 05-19-2013 05:05 PM

In that code fragment, you set i=0 but fail to increment it, so it looks like an infinite loop...

As to your specific question, consider this:
Code:

$ cat ramsvi
#!/bin/bash
arr=(File_1234.csv File_12sd45rg.csv)

len=${#arr[@]}
echo $len

shopt -s extglob

pattern0=*[0-9]*.*
pattern1=*[0-9]*_[0-9]*.*
pattern2=*[a-zA-z0-9]*.*
pattern3=File_[0-9]*_[0-9]*.csv
pattern4=File_[a-zA-Z]*_[a-zA-Z]*.csv
pattern5=File_[a-zA-Z0-9]*_[a-zA-Z0-9]*.csv
pattern6=File_[0-9]*[a-zA-Z]*.csv

for ((i=0; i<len; ++i))
do
  echo ${arr[${i}]}
  case ${arr[${i}]} in
    (${pattern0}) echo "pattern0 match" ;;&
    (${pattern1}) echo "pattern1 match" ;;&
    (${pattern2}) echo "pattern2 match" ;;&
    (${pattern3}) echo "pattern3 match" ;;&
    (${pattern4}) echo "pattern4 match" ;;&
    (${pattern5}) echo "pattern5 match" ;;&
    (${pattern6}) echo "pattern6 match" ;;
    (*) echo "No match.";;
  esac
  i=$((++${i}))
done
$ bash ramsavi
2
File_1234.csv
pattern0 match
pattern2 match
No match.
File_12sd45rg.csv
pattern0 match
pattern2 match
pattern6 match

So, your question is "Why does pattern2 match in the second case?" But "*" in a bash pattern means "match anything," so *[0-9]*.* means "match anything containing a number anywhere before a dot" which always matches your file names.

Anyhow, why are you using a shell script for this task? There are several other languages that could, I think, be better used for this problem. (e.g., sed, gawk, grep, etc.)

konsolebox 05-20-2013 04:15 AM

I think this is just a duplicate of this thread.


All times are GMT -5. The time now is 02:22 PM.