此文档为旧博客搬运。——2020.05.11

好吧,在处理一些无聊的文件,需要把当前目录下所有子文件中的文件名都提取出来,不要文件的完全路径。批处理命令如下:

@ECHO OFF

REM %1 is the input filename for the output
REM if file exists, delete it
IF EXIST %1 (
	DEL %1
	)

FOR /D /r %%G IN ("*") Do (
	CD %%G
	REM append the file list name to filelist
	DIR /B >> ../%1
	CD ..)

ECHO DONE

其中 >> 表示把dir的输出append到已有的文件里面。把上述文件命名为 listfile.bat 。在cmd 里面输入 listfile filelist.dat,则所有文件的输出都在filelist.dat 文件里面。

上述命令行有个问题:如果文件名有数字,如1,2,...,n,则输出时候会出现112前面的情况。因为dir并不是自然排序。一种方法是把文件名数字前面补0 (可再写batch file 或者用Total Commander批量重命名),或者,直接用ls -cv bash 命令来吧……

#!/bin/bash
# no space before and after =
filename=filelist.txt

# remove the file if it already exists
if [ -f $filename ]
then
	rm $filename
fi

for dir in */
do
	cd $dir
	ls -cv | sed -e 's/\.\(doc\|docx\)$//' >> ../$filename
	cd ..
done
echo "done"

sed部分主要用来去掉.doc.docx的扩展。另:bash文件用./bashfilename来运行。

参考