How to Output a List of Files to a File and Sort Them in Linux



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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值