Introduction
Have you ever wondered how to dump thousands of files to a text file and sort them alphabetically? This tutorial will show you how to do it and create a bash script.
Listing Your Files Recursively
The command I will be using to list all the files is find. To list all the files recursively in a directory use:
find /your/path
List AVI Files Only
To list all files with a certain file extension recursively use the -name option in find:
find /your/path -name *.avi
List Just The Files
To output just the file names and not the directory path add -printf “%f\n” to the end:
find /your/path -name *.avi -printf "%f\n"
The directories will still be listed as find enters the directory. To have only the files listed add -type f to find:
find /your/path -name *.avi -type f -printf "%f\n"
Sorting The List Alphabetically
To sort the list alphabetically, pipe the output to sort:
find /your/path -name *.avi -type f -printf "%f\n" | sort
Output The List To A File
To output the list to a file just add > /path/to/file.txt to the end:
find /your/path -name *.avi -type f -printf "%f\n" | sort > /path/to/file.txt
Adding What We Have Learnt To A Script
The script is going to take a command line argument which is the directory path to list, list the files recursively, sort them alphabetically and output them to the second command line argument which is the file to output to:
#!/bin/bash echo "dumping a list of files from '$1' to '$2'" echo "starting..." find $1 -type f -printf "%f\n" > $2 echo "finished."
The output will be something like this:
./dumpfiles /Repository/Media/Media1/TV/ ~/Desktop/test.txt dumping a list of files from '/Repository/Media/Media1/TV/' to '/home/bill/Desktop/test.txt' starting... finished.