1

I used find to make a text file containing everything on an external hard drive that has the .mp3 and .wma extension. I wanted to try using grep on the file in order to view the files without the preceding directories (just the lines themselves, it will look less cluttered). However, when i type this:

grep -h "*.mp3" mp3sCIR.txt 

nothing pops up. Yes, it's spelled correctly, and the file does actually contain the listing. I tried removing the -h and still nothing. Egrep works but does not suppress filename/path like requested.

2

First, you seem to be misunderstanding what the -h flag does.

-h will suppress the name(s) of the files passed on the command line (i.e. mp3sCIR.txt - although when only a single file is given, the name is not printed by default) - it won't remove anything from the names of the files inside the file.

Second, you are confusing shell patterns (aka 'globs') and regular expressions - grep uses regex syntax, so to match filenames with the .mp3 extension you'd need1

grep ".*\.mp3" mp3sCIR.txt 

(which should work the same with or without the -E, since the basic and extended forms are identical).

To remove the leading pathname components (i.e. what you were attemtping to do with -h) you could use

grep -o "[^/]*\.mp3"  mp3sCIR.txt

to print only the matching portion not including path separators, or with grep in perl compatible (PCRE) mode

grep -Po ".*/\K.*\.mp3" mp3sCIR.txt


For future reference, you could have saved the names without leading path components by using find's -printf '%f\n' output format.


[1] Actually it seems like while BRE treats a bare * at the start of a pattern as literal, ERE (i.e. egrep/grep -E) appears to treat it as a quantifier for an empty expression ("zero or more instances of nothing"); hence grep -E "*.mp3" does match entries with the .mp3 suffix - but not for the reason you'd probably think.

  • would you kindly tell me how i would use find's -printf argument in this instance? Thanks in advance. – thinksinbinary Aug 26 '16 at 20:15
  • @thinksinbinary something like find path/to/dir \( -name '*.mp3' -o -name '*.wma' \) -printf '%f\n' > mp3s_wmas.txt – steeldriver Aug 26 '16 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.