简体   繁体   中英

How do I use grep in the terminal to print a list of files matching a specific grep pattern?

For a school project, I have to SSH into a folder on the school server, the usr/bin folder which has a list of files, then print a list of files that start with "file". I know Regex half-decently, at least conceptually, but I'm not sure of the UNIX command to do this.

I tried grep '^[file][a-zA-Z0-9]*' (start of a line, letters file, then 0 or more occurrences of any other number or digit) but that doesn't seem to work.

Help?

You can use find command for this once you are connected to your school server.

find /usr/bin -type f -name "file*"

How would I do it if I wanted all files that started with a OR b, and ended with a OR b

Using find:

find /usr/bin -type f -regex "^[ab].*[ab]$" 

Using ls and grep :

ls -1 /usr/bin | grep "^[ab].*[ab]$"

You should be able to use a simple ls command to get this information.

cd /usr/bin
ls -1 file*

For more complex matches, you could pipe the output of ls to grep, but wwomack's solution is simplest for your scenario.

# for file names starting with "file"
ls /usr/bin | grep ^file
# more complex file names
ls /usr/bin | grep "^[ab].*[ab]$"
# files that do not start with alphabetic characters
ls -a | grep ^[^a-zA-Z]

grep works on the contents of files, not file names. But, using pipes (|), you are able to treat the output (referred to as stdout) of one command as an input file (stdin) to another command.

You'll want to study regular expressions (and grep) more on your own, but here are some basics. First, grep operates on a line-by-line basis, comparing each line to the regex and printing it if it matches. At the beginning of the regex ^ anchors the match to the beginning of the line; at the end, $ anchors it to the end. If the regex pattern does not begin or end with these symbols then any subsequence of the line that matches the pattern causes the line to match.

For example, grep ^file$ only matches if the line only contains the word file while grep file matches any line that contains the word file anywhere. grep file$ matches lines that end with the word file with 0 or more characters before it.

Regarding your question, "whose names do not start with either a lowercase or an uppercase English letter" your command could be much simplified (see third example), but also notice that you begin the pattern with $ : since $ matches the end of the line, your regex is impossible. One final note, in my example, I used ls -a to return all files including hidden . files. On Unix and Linux systems, if the first character of the file name is a dot, then the file will not normally show up when listing a directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM