Linux Command Line Grep
Greetings, I just started learning the Linux command-line, I am reading a book on it and today I learned a little about pipelines, redirection and a little about grep. I tried the example out of the book and it worked as expected but as I tried an example for myself, the results were not as I had expected. In the following I tried to filter out the results of the “ls” command with “grep” to only show files containing the characters '.c',
In my folder /home/linus/prog where I keep my C programming source-files, amongst other things, I ran the following command: $ ls | grep .c and the results: booksrc booksrc.zip char_array2.c convert2.c convert.c datatype_sizes.c firstprog.c myrwprog.c pointer.c project testc First off I am sure there are dozens of more efficient and better ways to accomplish this simple task but I am trying to learn the basics, in particular "grep". Anyway why does booksrc,booksrc.zip, project, and testc all show up? Does grep ignore non-alphabetic characters? Or maybe '.' is some wild card I am unaware of? Thank-you very much for the help in advance. |
Quote:
|
Hey BigRigDriver, thanks for the quick answer. I appreciate it.
|
grep uses regular expressions for pattern matching, and in regex, a '.' has the special meaning of 'any single character'.
To get the list you want, use a bracket expression to isolate the character and treat it as a literal value, or backslash it, or use the '-F' option to force it to be treated as a literal string. Code:
ls | grep '[.]c' http://mywiki.wooledge.org/Arguments http://mywiki.wooledge.org/WordSplitting http://mywiki.wooledge.org/Quotes In any case, while the above may be good for practice, file listing and processing should almost always be done with globbing patterns instead, or find, if you need more advanced matching (and be sure to use null separators when you do). You should never depend on parsing ls for lists of files or their metadata. |
use this
Quote:
|
David the H, clocker, thanks for the answer and especially David for the information and the links you've provided. I've bookmarked that website and will use it for further reference.
|
Except that (sorry to say) clocker's command is completely wrong, for the reasons explained before. grep does not support simple globbing patterns like that, only regex or fixed strings.
And again, you shouldn't be using ls for things like this anyway. Other than that, good for you. Greg's wiki is perhaps the very best scripting site I've ever found, with bash-hackers.org coming in a close second. |
All times are GMT -5. The time now is 01:43 AM. |