Reputation: 6933
I am looking for a way to list all the files in a directory excluding directories themselves, and the files in those sub-directories.
So if I have:
./test.log
./test2.log
./directory
./directory/file2
I want a command that returns: ./test.log ./test2.log and nothing else.
Upvotes: 49
Views: 63316
Reputation: 21921
One more option
ls -ltr | grep ^-
to list all files, while
ls -ltr | grep ^d
to list all directories
Upvotes: -1
Reputation: 53065
find
only regular filesUse the -type f
option with find
to find only regular files. OR, to be even more-inclusive, use -not -type d
to find all file types except directories.
When listing all files, I like to also sort them by piping to sort -V
, like this:
# find only regular files
find . -type f | sort -V
# even more-inclusive: find all file types _except_ directories
find . -not -type d | sort -V
From man find
:
-type c
File is of type
c
:
b
- block (buffered) specialc
- character (unbuffered) speciald
- directoryp
- named pipe (FIFO)f
- regular filel
- symbolic link; this is never true if the-L
option or the-follow
option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when-L
is in effect, use-xtype
.s
- socketD
- door (Solaris)To search for more than one type at once, you can supply the combined list of type letters separated by a comma
,
(GNU extension).
find
(a multi-line string list of files) into a bash arrayTo take this one step further, here is how to store all filenames into a bash indexed array called filenames_array
, so that you can easily pass them to another command:
# obtain a multi-line string of all filenames
filenames="$(find . -type f | sort -V)"
# read the multi-line string into a bash array
IFS=$'\n' read -r -d '' -a filenames_array <<< "$filenames"
# Now, the the variable `filenames_array` is a bash array which contains the list
# of all files! Each filename is a separate element in the array.
Now you can pass the entire array of filenames to another command, such as echo
for example, by using "${filenames_array[@]}"
to obtain all elements in the array at once, like this:
echo "${filenames_array[@]}"
OR, you can iterate over each element in the array like this:
echo "Files:"
for filename in "${filenames_array[@]}"; do
echo " $filename"
done
Sample output:
Files:
./file1.txt
./file2.txt
./file3.txt
find . -type f
from the main answer by @John Kugelman here.Upvotes: 2
Reputation: 4985
$ find . -type f -print
Each file will be on its own line. You must be in the directory you want to search.
Upvotes: 0
Reputation: 9213
If you need symlinks, pipes, device files and other specific elements of file system to be listed too, you should use:
find -maxdepth 1 -not -type d
This will list everything except directories.
Upvotes: 21
Reputation: 361997
If you want test.log
, test2.log
, and file2
then:
find . -type f
If you do not want file2
then:
find . -maxdepth 1 -type f
Upvotes: 86