【问题标题】:How to perform sort on all files in a directory?如何对目录中的所有文件进行排序?
【发布时间】:2013-08-26 11:35:00
【问题描述】:

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

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

【问题讨论】:

    标签: file unix sorting directory cat


    【解决方案1】:

    使用find-exec

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

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

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

    【讨论】:

    • 这会为文件夹中的每个输入文件输出一个单独的文件吗?以及如何使输出文件转到子目录而不是包含原始文件的父目录?
    【解决方案2】:

    你可以这样写一个脚本:

    #!/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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2011-08-01
      • 1970-01-01
      • 2011-07-04
      相关资源
      最近更新 更多