how to find hidden file
-
11-10-2019 - |
Question
i have some files, they are named like this
.abc efg.txt
.some other name has a dot in front.txt
......
and i want to do something like this
for i in `ls -a` ; do echo $i; done;
i expected the result should be
.abc efg.txt
.some other name has a dot in front.txt
but it turns out a buch of mess.. how can i get those hidden file???
thanks
Solution
Instead of using ls
use shell pattern matching:
for i in .* ; do echo $i; done;
If you want all files, hidden and normal do:
for i in * .* ; do echo $i; done;
(Note that this will als get you .
and ..
, if you do not want those you would have to filter those out, also note that this approach fails if there are no (hidden) files, in that case you would also have to filter out *
and .*
)
If you want all files and do not mind using bash
specific options, you could refine this by setting dotglob
and nullglob
. dotglob
will make *
also find hidden files (but not .
and ..
), nullglob
will not return *
if there are no matching files. So in this case you will not have to do any filtering:
shopt -s dotglob nullglob
for i in * ; do echo $i; done;
OTHER TIPS
to avoid .
and ..
you can do:
find . -name ".*" -type f -maxdepth 1 -exec basename {} ";"
This will print what you want. If you need to do something more than echo
, just put it as an argument for exec
.
for fname in .*; do echo $fname; done;
will print .
and ..
as well.
To find hidden files use find:
find . -wholename "./\.*"
To exclude them from the result:
find . -wholename "./\.*" -prune -o -print
And another way to handle whole files with spaces is to treat them as lines:
ls -1a | while read aFileName
do
echo $aFileName
done