Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globbing for only files in Bash

Tags:

bash

glob

I'm having a bit of trouble with globs in Bash. For example:

echo *

This prints out all of the files and folders in the current directory. e.g. (file1 file2 folder1 folder2)

echo */

This prints out all of the folders with a / after the name. e.g. (folder1/ folder2/)

How can I glob for just the files? e.g. (file1 file2)

I know it could be done by parsing ls but also know that it is a bad idea. I tried using extended blobbing but couldn't get that to work either.

like image 523
John P Avatar asked Dec 23 '13 14:12

John P


People also ask

Can globbing patterns be applied to contents of a file?

You can use different types of globbing patterns for searching particular content from a file. 'grep' command is used for content searching in bash.

How do you write a bash shell loop over a set of files?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I list files in a directory in bash?

To see a list of all subdirectories and files within your current working directory, use the command ls .

How do I loop through a file?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.


2 Answers

WIthout using any external utility you can try for loop with glob support:

for i in *; do [ -f "$i" ] && echo "$i"; done
like image 163
anubhava Avatar answered Oct 31 '22 17:10

anubhava


I don't know if you can solve this with globbing, but you can certainly solve it with find:

find . -type f -maxdepth 1
like image 38
Oliver Charlesworth Avatar answered Oct 31 '22 18:10

Oliver Charlesworth