Answers:
下面的python脚本可以完成这项工作。隐藏的文件和不带扩展名的文件分别存储在一个文件夹中。
由于它可能用于更广泛的用途,因此我添加了一些选项:
exclude = ()
remove_emptyfolders = True
或False
)shutil.move(subject, new_dir+"/"+name)
通过:
shutil.copy(subject, new_dir+"/"+name)
剧本:
#!/usr/bin/env python3
import os
import subprocess
import shutil
# --------------------------------------------------------
reorg_dir = "/path/to/directory_to_reorganize"
exclude = (".jpg") # for example
remove_emptyfolders = True
# ---------------------------------------------------------
for root, dirs, files in os.walk(reorg_dir):
for name in files:
subject = root+"/"+name
if name.startswith("."):
extension = ".hidden_files"
elif not "." in name:
extension = ".without_extension"
else:
extension = name[name.rfind("."):]
if not extension in exclude:
new_dir = reorg_dir+"/"+extension[1:]
if not os.path.exists(new_dir):
os.mkdir(new_dir)
shutil.move(subject, new_dir+"/"+name)
def cleanup():
filelist = []
for root, dirs, files in os.walk(reorg_dir):
for name in files:
filelist.append(root+"/"+name)
directories = [item[0] for item in os.walk(reorg_dir)]
for dr in directories:
matches = [item for item in filelist if dr in item]
if len(matches) == 0:
try:
shutil.rmtree(dr)
except FileNotFoundError:
pass
if remove_emptyfolders == True:
cleanup()
如果存在不必要的覆盖重复文件的风险
以一些额外的行为代价,我们可以防止覆盖可能的重复项。使用下面的代码,重复项将重命名为:
duplicate_1_filename, duplicate_2_filename
等等
剧本:
#!/usr/bin/env python3
import os
import subprocess
import shutil
# --------------------------------------------------------
reorg_dir = "/path/to/directory_to_reorganize"
exclude = (".jpg") # for example
remove_emptyfolders = True
# ---------------------------------------------------------
for root, dirs, files in os.walk(reorg_dir):
for name in files:
subject = root+"/"+name
if name.startswith("."):
extension = ".hidden_files"
elif not "." in name:
extension = ".without_extension"
else:
extension = name[name.rfind("."):]
if not extension in exclude:
new_dir = reorg_dir+"/"+extension[1:]
if not os.path.exists(new_dir):
os.mkdir(new_dir)
n = 1; name_orig = name
while os.path.exists(new_dir+"/"+name):
name = "duplicate_"+str(n)+"_"+name_orig
n = n+1
newfile = new_dir+"/"+name
shutil.move(subject, newfile)
def cleanup():
filelist = []
for root, dirs, files in os.walk(reorg_dir):
for name in files:
filelist.append(root+"/"+name)
directories = [item[0] for item in os.walk(reorg_dir)]
for dr in directories:
matches = [item for item in filelist if dr in item]
if len(matches) == 0:
try:
shutil.rmtree(dr)
except FileNotFoundError:
pass
if remove_emptyfolders == True:
cleanup()
考虑到OP,我们所有人都忘记添加有关如何使用的说明。由于可能会(并且确实会)出现重复的问题,因此仍然可能有用。
reorganize.py
在脚本的开头部分,设置目标目录(带有要重组的文件):
reorg_dir = "/path/to/directory_to_reorganize"
(如果目录包含空格,请使用引号)
您想排除的可能扩展(可能没有,如下所示):
exclude = ()
然后,如果您想删除空文件夹:
remove_emptyfolders = True
使用以下命令运行脚本:
python3 /path/to/reorganize.py
注意:如果您要复制文件而不是move,请替换:
shutil.move(subject, new_dir+"/"+name)
通过:
shutil.copy(subject, new_dir+"/"+name)
请先尝试少量样品。
您可以使用find
稍微复杂的exec
命令:
find . -iname '*?.?*' -type f -exec bash -c 'EXT="${0##*.}"; mkdir -p "$PWD/${EXT}_dir"; cp --target-directory="$PWD/${EXT}_dir" "$0"' {} \;
# '*?.?*' requires at least one character before and after the '.',
# so that files like .bashrc and blah. are avoided.
# EXT="${0##*.}" - get the extension
# mkdir -p $PWD/${EXT}_dir - make the folder, ignore if it exists
更换cp
用echo
的预演。
更加有效和整洁的方法是将bash
命令保存在脚本中(例如,位于 /path/to/the/script.sh
):
#! /bin/bash
for i
do
EXT="${i##*.}"
mkdir -p "$PWD/${EXT}_dir"
mv --target-directory="$PWD/${EXT}_dir" "$i"
done
然后运行find
:
find . -iname '*?.?*' -type f -exec /path/to/the/script.sh {} +
这种方法非常灵活。例如,要使用文件名而不是扩展名(filename.ext
),可将其用于EXT
:
NAME="${i##*/}"
EXT="${NAME%.*}"
*.fig.bak
或” .profile/.bashrc
,但至少应至少处理带有扩展名的文件。谢谢。
ls | gawk -F. 'NF>1 {f= $NF "-DIR"; system("mkdir -p " f ";mv " $0 " " f)}'
计算扩展列表(移动后):
ls -d *-DIR
计算扩展列表(移动之前):
ls -X | grep -Po '(?<=\.)(\w+)$'| uniq -c | sort -n
(在最后一个示例中,我们正在计算每个扩展名的文件数并对其进行排序)
ls -X
。关于我为什么反对的建议ls
,请参见unix.stackexchange.com/q/128985/70524和unix.stackexchange.com/q/112125/70524。为了完成您的工作,我会走更长的路:(如果需要计数,可以find . -type f -name '*?.?*' -print0 | sed -z 's/.*\.//' | sort -zu
使用可选的| uniq -cz
)。并且find ... -print0 | gawk -v RS='\0'
(尽管那不是很便携)。
试试这个shell脚本。
#!/bin/sh
src=`dirname "$1"`/`basename "$1"`;
for file in "$src"/*?.?*; do
if test -f "$file"; then
dest="$src${file##*.}"_files;
mkdir -p "$dest";
mv "$file" "$dest";
fi;
done;
# pass the directory to re-organize as first argument
# moves only regular files which have extension
# ignores other type of files including
# files having no extension, hidden files, directories, and links.
filepath
用file
。我会直接纠正。
for file in "$src"/*?.?*; do ..
read
可能会有意外的行为。您还应该在mkdir和mv命令中引用变量。
for i in *; do printf "%s\n" "$i"; done; for i in $(ls -d); do printf "%s\n" "$i"; done
-iname '*.*'
应采取的极端案例,我担心......好主意小心!