Click to See Complete Forum and Search --> : Probably easy reg exp question in simple script


soleblazer
01-02-2004, 02:51 PM
Greetings,

I am sure this is easy, but I am having brain fry today.

I want to write a simple alias that will only display the directories in a location.

I realize that there are many ways to do this, but I went do the road of doing something like:

for i in `ls -l`
do
if [[ $i starts with d ]]
then
echo $i
fi
done

Now, my question is, how can I do the part with the "if $i begins with d" part.

I realize I could probably do something with awk (slicing the first letter off), but is there a easy way to do this with regexp? maybe iwth the ^ ???

Tks, this is more of a learning thing for me now.

Strike
01-02-2004, 03:06 PM
Just pipe ls through egrep and use the regexp "^d".

ls -l | egrep "^d"

No need to get into silly scripting. UNIX philosophy, man!
:)

soleblazer
01-02-2004, 03:12 PM
*Smacks head*

Thanks, I can't believe I forgot about egrep

bwkaz
01-02-2004, 08:22 PM
find . -type d -maxdepth 1

If you want only the directory names (and not any of the other stuff that "ls -l" prints).

ernieg
01-02-2004, 08:45 PM
Here's a quick way to do what you want...

# First for X in * means for every file in the current dir
for X in *
do
if [ -d "$X" ] # This will test if the file is a directory
then
echo $X #echo the file to stdout
fi
done

There is a plethora of options to the "test" command in the bash shell. Test gets invoked by the "[ ]" square brackets in an "if" statement. Check the man page and you'll see what I mean.

Good luck and enjoy!

apeekaboo
01-04-2004, 07:48 AM
I made two scripts to do this in slightly diffirent ways some time ago:
If no directories are supplied to the scripts, they show a list of the available dirs in the current directory.
It's possible to supply one or more directories to the command and the show what directories are present there.

They don't work when supplying directory names containing whitespace, but I think that would be easy to fix by changing $IFS, but I haven't bothered since I usually just interested in what's inte the current dir... :)

Here's the first script:

apeekaboo
01-04-2004, 07:49 AM
...and here's the other one (for long lists):