Ian*_*anG 3 command-line scripts batch-rename
I 系统生成的具有通用文件名的文件。我想要一个可以运行的脚本,它会扫描这些文件中 ProcID 一词的第二个实例(在 ProcID 一词之后是一个数字),然后使用 ProcID 编号重命名该文件。目前我有以下几点:
FILEPATH; awk -F '[:)]' '/ProcID./{printf "mv %s %s.txt\n", FILENAME, $2 | "/bin/sh"; nextfile}' O*.TXT
Run Code Online (Sandbox Code Playgroud)
例如,脚本扫描文件并找到第二个实例,(ProcID:0000014778)然后使用此过程 ID 号重命名文件。
上面的脚本只找到第一个实例,因此在系统完成输出到文件之前文件被重命名。
下面的脚本将目录中的所有文件重命名为第二个找到的字符串中的id,以 开头ProcID::
#!/usr/bin/env python3
import shutil
import os
import sys
dr = sys.argv[1]
for f in os.listdir(dr):
file = os.path.join(dr, f)
try:
# only rename if the second instance exists
new = [s for s in open(file).read().split() if s.startswith("(ProcID:")][1]
except (IndexError, IsADirectoryError):
pass
else:
# rename the file
shutil.move(file, os.path.join(dr, new.split(":")[-1].strip()[:-1]))
Run Code Online (Sandbox Code Playgroud)
rename_files.py以目录为参数运行它:
python3 /path/to/rename_files.py /path/to/directory_with_files
Run Code Online (Sandbox Code Playgroud)ProcID:0000014778ProcID...然后使用下面的版本,它只会重命名.txt文件并将扩展名保留在重命名的文件中。用法完全一样。
python3 /path/to/rename_files.py /path/to/directory_with_files
Run Code Online (Sandbox Code Playgroud)
它列出了目录中的文件:
for f in os.listdir(dr)
Run Code Online (Sandbox Code Playgroud)列出文件内的字符串,以 ProcID:
new = [s for s in open(file).read().split() if s.startswith("(ProcID:")][1]
Run Code Online (Sandbox Code Playgroud)
结尾[1]提取第二次出现的字符串,从ProcID:([0]是第一个)
id的分割:
new.split(":")[-1].strip()
Run Code Online (Sandbox Code Playgroud)并使用 id 重命名文件:
shutil.move(file, os.path.join(dr, new.split(":")[-1].strip()[:-1]))
Run Code Online (Sandbox Code Playgroud)Python2 版本的脚本 1. OP 安装了 python2,这需要IOError而不是IsADirectoryError防止脚本运行到目录而不是文件中的错误。
#!/usr/bin/env python3
import shutil
import os
import sys
dr = sys.argv[1]
for f in os.listdir(dr):
file = os.path.join(dr, f)
try:
# only rename is the second instance exists
new = [s for s in open(file).read().split() if all([
s.startswith("(ProcID:"), f.endswith(".txt")
])][1]
except (IndexError, IsADirectoryError):
pass
else:
shutil.move(file, os.path.join(dr, new.split(":")[-1].strip()[:-1]+".txt"))
Run Code Online (Sandbox Code Playgroud)
...为了完整,第二个脚本的python2版本:
for f in os.listdir(dr)
Run Code Online (Sandbox Code Playgroud)