x=$(find . -name "*.txt")
echo $x
if I run the above piece of code in Bash shell, what I get is a string containing several file names separated by blank, not a list.
Of course, I can further separate them by blank to get a list, but I'm sure there is a better way to do it.
So what is the best way to loop through the results of a find
command?
Note: this method and the (second) method shown by bmargulies are safe to use with white space in the file/folder names.
In order to also have the - somewhat exotic - case of newlines in the file/folder names covered, you will have to resort to the
-exec
predicate offind
like this:The
{}
is the placeholder for the found item and the\;
is used to terminate the-exec
predicate.And for the sake of completeness let me add another variant - you gotta love the *nix ways for their versatility:
This would separate the printed items with a
\0
character that isn't allowed in any of the file systems in file or folder names, to my knowledge, and therefore should cover all bases.xargs
picks them up one by one then ...How about if you use grep instead of find?
Now you can read this file and the filenames are in the form of a list.