Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using grep and ls -a commands

Using an ls –a and grep, how would you list the name of all of the files in /usr starting with the letter p or the letter r or the letter s using a single grep command?

would this be right?

ls –a | grep [prs] /usr
like image 495
Nicole Romain Avatar asked May 28 '15 18:05

Nicole Romain


People also ask

What does grep command do?

The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.

What is the difference between grep and find commands?

The main difference between the two is that grep is used to search for a particular string in a file whereas find is used to locate files in a directory, etc. also you might want to check out the two commands by typing 'man find' and 'man grep'.


2 Answers

 ls -a /usr | grep '^[prs]'

Would select from the output of ls -a /usr (which is the list of files in /usr delimited by newline characters) the lines that start by either of the p, r or s characters.

That's probably what your teacher is expecting but it's wrong or at least not reliable.

File names can be made of many lines since the newline character is as valid a character as any in a file name on Linux or any unix. So that command doesn't return the files whose name starts with p, q or s, but the lines of the filenames that start with p, q or s. Generally, you can't post-process the output of ls reliably.

-a is to include hidden files, that is files whose name starts with .. Since you only want those that start with p, q or s, that's redundant.

Note that:

ls /usr | grep ^[pqs]

would be even more wrong. First ^ is a special character in a few shells like the Bourne shell, rc, es or zsh -o extendedglob (though OK in bash or other POSIX shells).

Then, in most shells (fish being a notable exception), [pqs] is a globbing operator. That means that ^[qps] is meant to be expanded by the shell to the list of files that match that pattern (relative to the current directory).

So in those shells like bash that don't treat ^ specially, if there is a file called ^p in the current directory, that will become

ls /usr | grep ^p

If there's no matching file, in csh, tcsh, zsh or bash -O failglob, you'll get an error message and the command will be cancelled. In zsh -o extendedglob where ^ is a globbing operator, ^[pqs] would mean any file but p, q or s.

like image 120
Stephane Chazelas Avatar answered Oct 25 '22 18:10

Stephane Chazelas


If you're trying to find files, don't use ls. Use the find command.

find /usr -name '[prs]*'

If you don't want to search the entire tree under /usr, do this:

find /usr -maxdepth 1 -name '[prs]*'
like image 29
Andy Lester Avatar answered Oct 25 '22 19:10

Andy Lester