2013-08-26 28 views
2

如何對目錄中的所有文件執行排序?如何對目錄中的所有文件執行排序?

我本來可以在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) 

回答

12

使用find-exec

find /somedir -type f -exec sort -o {} {} \; 

爲了限制sort在目錄本身的文件,使用-maxdepth

find /somedir -maxdepth 1 type f -exec sort -o {} {} \; 
0

您可以編寫一個腳本:

#!/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 
相關問題