4

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

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

2 回答 2

17

使用find-exec

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

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

find /somedir -maxdepth 1 -type f -exec sort -o {} {} \;
于 2013-08-26T11:43:38.900 回答
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
于 2013-08-26T11:45:29.610 回答