tags:

views:

947

answers:

8

I just want to get the files from the current dir and only output .mp4 .mp3 .exe files nothing else. So I thought I could just do this:

ls | grep \.mp4$ | grep \.mp3$ | grep \.exe$

But no, as the first grep will output just mp4's therefor the other 2 grep's won't be used.

Any ideas?

PS, Running this script on Slow Leopard.

+9  A: 

egrep -- extended grep -- will help here

ls | egrep '\.mp4$|\.mp3$|\.exe$

should do the job.

mobrule
+1 you got it in 34 seconds before me
Jonathan Fingland
Thats it!ThanksJust realized I should have it case insensitive, so I'm using:ls | egrep -i '\.mp4$|\.mp3$|\.exe$Incase anyone else needs help with that one day.Im always surprised by the speed I get my answer on here.
Mint
I can't see how this would work. ls without any options produces output in columns. Anchoring to the end of the line will not match properly.
camh
@camh: `ls` to a terminal (or with `-C` option) produces multi-column output. `ls` to a pipe (or with `-1`) has single column output. (Compare output of `ls` with `ls | cat`).
mobrule
+1  A: 
ls | grep "\.mp4$
\.mp3$
\.exe$"
Jeff Mc
Could you explain the down vote please?
Jeff Mc
Thanks, but a bit inconvenient using up several lines.
Mint
+5  A: 

the easiest way is to just use ls

ls *.mp4 *.mp3 *.exe
Good Time Tribe
Thanks, but I already tried that and I didn't like the errors you get when there is no file.Thou I could of fixed that by doing:ls *.mp4 *.mp3 *.exe 2> /dev/nullOnly thought of that now thou :P
Mint
I am surprised that `ls` doesn't have some sort of silent option.
MitMaro
None that I could find.
Mint
In bash, you can do "set -o nullglob", and you wont get the errors.
camh
My mistake - that should be "shopt -s nullglob" not the set -o command
camh
Or just use "echo": echo *.mp4 *.mp3 *.exe
Adrian Pronk
+4  A: 

No need for grep. Shell wildcards will do the trick.

ls *.mp4 *.mp3 *.exe

If you have run

shopt -s nullglob

then unmatched globs will be removed altogether and not be left on the command line unexpanded.

If you want case-insensitive globbing (so *.mp3 will match foo.MP3):

shopt -s nocaseglob
camh
Same comment as I gave to Good Time Tribe.
Mint
+1  A: 

Just in case: why don't you use find?

find -iname '*.mp3' -o -iname '*.exe' -o -iname '*.mp4'
Pavel Shved
A: 

In case you are still looking for an alternate solution:

ls | grep -i -e "\.tcl$" -e "\.exe$" -e "\.mp4$"

Feel free to add more -e flags if needed.

Hai Vu
+2  A: 

Why not:

ls *.{mp3,exe,mp4}

I'm not sure where I learned it - but I've been using this.

meder
+3  A: 

Use regular expressions with find:

find . -iregex '.*\(mp3\|mp4\|exe\)' -printf '%f\n'

If you're piping the filenames:

find . -iregex '.*\(mp3\|mp4\|exe\)' -printf '%f\0' | xargs -0 dosomething

This protects filenames that contain spaces or newlines.

Dennis Williamson