如何对目录中的所有文件执行排序?

时间:2013-08-26 11:35:00

标签: file unix sorting directory cat

如何对目录中的所有文件执行排序?

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

2 个答案:

答案 0 :(得分:15)

使用find-exec

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

要将sort限制为目录中的文件,请使用-maxdepth

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

答案 1 :(得分: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
相关问题