Link to home
Start Free TrialLog in
Avatar of FrEaK85
FrEaK85

asked on

Shell programing and regular expressiong: -> grep

Ok, what I need to do is: list all files in a given directory with a given extension

$1 = directory
$2 = extension

I want to use regular expression for this, so I used the command
filelist = `ls $1 | grep '.*[\\\\.]$2$'`

the problem is, the $ from $2 conflicts with the $ from the regular expression

What I've already tried:
- putting the command in a dummy variable as a string and then execute it
- putting all sort of quotes around it
- banging my head on the table

PS: it works if I replace $2 with the actual extension
This is a school assignment so I can't use any other language or so

Hope someone can help me,

thanks,

Walter
ASKER CERTIFIED SOLUTION
Avatar of glassd
glassd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
filelist = `ls $1 | grep ".*[\\\\.]$2$''`
also after setting $1 and $2, do not forget to export them.
and run the above command, it is working onmy system.
did ot work, please update.
Avatar of glassd
glassd

Patience.

Still don't see why you need to invoke grep when ls was written to do what you want.
try it using eval before grep as follows

var1=directory
var2=extension

filelist=`ls | eval grep '.*[\\\\.]$var2$'`

I think, this  should work

rgds,
Sanjeev
Avatar of yuzh
You don't need to use grep, just simply use:

filelist=`/bin/ls ${1}/*.${2}`

PS: use the full path to ls (do a which ls to find out), in case you have
      set aliase for ls.

Actually, there's no need to use 'ls', either. Expanding wildcards (sometimes called globbing) is something the shell does and in all of these formulations using ls, it's really the shell doing the work.

filelist=$(echo $1/*.$2)

As for the way to get your original formulation to work, you need to protect the $ that was intended to be an end-of-string marker from being prematurely taken by the shell as a variable substitution. You seemed to have some concept of this given the number of backslashes you put before that . in the square brackets...but here's a version that worked for me:

filelist=`ls $1 | egrep ".*\\.$2\$"`

The various shells differ a bit in whether variable interpolation takes place inside single quotes inside backticks. To be safe, I stuck to double-quotes.

Avatar of FrEaK85

ASKER

filelist=`ls $1/*.$2` => feeling stupid stupid stupid