Reputation: 1086
I am writing a small shell script. there i want to get all the paths of files recursively. for that i am using bellow code.
for entry in `find . -type f`; do
echo $entry
done
getting the files recursively is okay. but it does not sort by path.
ex : the folder has 1,2,3,rename.sh (The shell script) files and a folder called test. inside that test folder again there are 1,2, 3 files. when i execute this code the out put is like this
./rename.sh
./1.png
./test/1.png
./test/2.jpg
./test/3.jpg
./2.jpg
./3.jpg
why is it not sorted by path. How do i sort it by the path so the out put wold be
./rename.sh
./1.png
./2.jpg
./3.jpg
./test/1.png
./test/2.jpg
./test/3.jpg
Upvotes: 0
Views: 1240
Reputation: 295363
If you want content sorted, do it yourself. For a list of files, doing that safely means NUL-delimiting the names (so a file with a newline in its name doesn't get read as the names of two separate files and thus split apart during the sort process), and using sort -z
(a GNU extension).
while IFS= read -r -d '' entry; do
printf 'Processing: %s\n' "$entry"
done < <(find . -type f -print0 | sort -z)
See Using Find for guidance on using find
reliably, and BashFAQ #1 for a discussion of the while read
construct used here.
Upvotes: 3