How to perform sort on all files in a directory?

alvas picture alvas · Aug 26, 2013 · Viewed 7.3k times · Source

How do I perform sort on all files in the directory?

I could have done it in python, but it seems to be too much of a hassle.

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)

Answer

devnull picture devnull · Aug 26, 2013

Use find and -exec:

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

For limiting the sort to the files in the directory itself, use -maxdepth:

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