Operating System - HP-UX
1833007 Members
2839 Online
110048 Solutions
New Discussion

Re: filename pattern matching

 
Mike Blansfield_1
New Member

filename pattern matching

Hello,

I need to write a script that will do pattern matching of filenames. The pattern to be matched is the first 3 characters of the file and they must have this pattern:

A=alpha N=numeric
ANN AAN ANA

Any help appreciated!

Mike
5 REPLIES 5
curt larson_1
Honored Contributor

Re: filename pattern matching

using dtksh you can do something like this

#!/usr/dt/bin/dtksh

while read filename
do
case $filename in
[:alpha:][:alnum:][:alnum:]*) print $filename;;
esac
done

of

if [[ "$filename" = [[:alpha:][:alnum:][:alnum:]]* ]] ;then
print $filename
fi
James R. Ferguson
Acclaimed Contributor

Re: filename pattern matching

Hi Mike:

I'll use regular expressions with 'awk' and 'ls' to generate the input:

# ls -l|awk '$NF~/^[[:alpha:]][0-9]][0-9]/ || $NF~/^[[:alpha:]][[:alpha:]][0-9]/ || $NF~/^[[:alpha:]][0-9]][[:alpha:]]/ {print $NF}'

This takes the output from 'ls' and examines the filename (the last field of each line) and prints it if it meets the criteria you specified for the first three characters. The '||' is an 'or' operator.

Regards!

...JRF...
curt larson_1
Honored Contributor

Re: filename pattern matching

or using sed

ls |
sed -n '/^[:alpha:][:alpha:,0-9]\{2\}/p'
Chris Vail
Honored Contributor

Re: filename pattern matching

ls -l [a-z] [0-9] [0-9] *| [a-z] [a-z] [0-9]*| [a-z] [0-9] [a-z] *

I haven't tested it, but this should work.
john korterman
Honored Contributor

Re: filename pattern matching

Hi,
I have tested this and it seems to work:
(should be on a single line with no spaces between ??? and ???):

# ls | egrep "^[[:alpha:]][[:digit:]][[:digit:]]|^[[:alpha:]][[:alpha:]][[:digit:]]|^[[:alpha:]][[:digit:]][[:alpha:]]"

It has the obvious advantage of being easy to read!
The output from ls is redirected to egrep, which tries to match the extended reg. expression described between ??? and ???
The expression itself holds three alternatives, separated from one another by a pipe character.
Each alternative starts with the hat/caret character, which means ???must start with this???.
The allowed character combination for each alternative is described by so-called character-classes, e.g. [:alpha:] meaning any alphabetical character. A class is always surrounded by colons and a set of square brackets.
What you put in between square brackets, in this case the ???outer??? square brackets, means ???match any single one of the character(s) mentioned.
Hence, match any one alphabethical character appearing at the beginning looks like this: ^[[:alpha:]]

regards,
John K
it would be nice if you always got a second chance