Using grep and ls -a Commands

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

Is it correct?

 ls –a | grep [prs] /usr 
+6
source share
5 answers

If you are trying to find files, do not use ls . Use the find .

 find /usr -name '[prs]*' 

If you do not want to search the entire tree under / usr, do the following:

 find /usr -maxdepth 1 -name '[prs]*' 
+4
source
  ls -a /usr | grep '^[prs]' 

Select from the output ls -a /usr (which is a list of files in /usr , separated by newlines), lines starting with the characters p , r or s .

Your teacher probably expects, but this is wrong or at least not reliable.

File names can be made up of many lines, as the newline character is as a valid character, like any in a file name on Linux or any unix. Thus, the command does not return files whose name begins with p , q or s , but file name strings starting with p , q or s . As a rule, you cannot reliably execute the output of ls .

-a must include hidden files, that is, files whose name begins with . . Since you only need those that start with p , q or s , this is redundant.

Note that:

 ls /usr | grep ^[pqs] 

will be even more erroneous. The first ^ is a special character in several shells, such as the Bourne, rc , es or zsh -o extendedglob bash (although OK in bash or other POSIX shells).

Then in most shells ( fish is the notable exception), [pqs] is the globbing operator. This means that ^[qps] supposed to be expanded by the shell into a list of files matching this pattern (relative to the current directory).

So, in those shells like bash that are not specifically related to ^ if there is a file in the current directory called ^p that will become

 ls /usr | grep ^p 

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

+3
source

The @twalberg comment is perfect for the options you asked. Echoes ignore hidden files, but they will be filtered out when you need files starting with [prs].
If you need hidden files for other filters, a similar solution would be ls -ad /usr/[prs]* , where the -d option suppresses the list of subdirectors.
This solution will also show the full path, it can be suppressed when you first go to the directory. If you want to stay in your current directory, use a subshell for it. I use && to skip ls when / usr dir does not exist.

 (cd /usr && ls -ad [prs]*) 
+2
source

I would ls in the directory and only then apply grep . In addition, you are missing the ^ character to filter out only those files that start with these letters:

 $ ls -a /usr | grep ^[prs] 
0
source

Why not just

  find /usr -type f -name '[prs]*' 
0
source

Source: https://habr.com/ru/post/988115/


All Articles