如何对目录中的所有文件进行排序?
我本可以在 python 中完成,但这似乎太麻烦了。
import os, glob
d = '/somedir/'
for f in glob.glob(d+"*"):
f2 = f+".tmp"
# unix~$ cat f | sort > f2; mv f2 f
os.system("cat "+f+" | sort > "+f2+"; mv "+f2+" "+f)
使用find
和-exec
:
find /somedir -type f -exec sort -o {} {} \;
要限制sort
目录本身中的文件,请使用-maxdepth
:
find /somedir -maxdepth 1 -type f -exec sort -o {} {} \;
您可以编写这样的脚本:
#!/bin/bash
directory="/home/user/somedir"
if [ ! -d $directory ]; then
echo "Error: Directory doesn't exist"
exit 1
fi
for file in $directory/*
do
if [ -f $file ]; then
cat $file | sort > $file.tmp
mv -f $file.tmp $file
fi
done