我有几个像这样的文件 -
* .ssss和* _passive.sss
如果我有一个名为blah1.sss和blah1_passive.sss的文件,我想摆脱blah1.sss并重命名为blah1_passive.sss。但是,如果我没有blah1_passive.sss,我想记录文件名并保留blah1.sss。
我能够找到所有* _passive.sss文件,但我想知道awk / sed etc命令可以将* _passive.sss重命名为* .sss。
编辑:现在我有这个,但os.rename不会覆盖文件,我需要覆盖它。
import os, fnmatch
def locate(pattern, root=os.curdir):
#ignore directories- uncomment to make ignore work
#ignored = ["0201", "0306"]
for path, dirs, files in os.walk(os.path.abspath(root)):
#for dir in ignored: # if dir in dirs: #dirs.remove(dir)
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
for filename in locate("*_passive.sss"):
#found the files that i want to rename, but os.rename() refuses to overwrite !!
newfilename=filename.rstrip("_passive.sss") + ".sss"
os.rename(filename,newfilename)
答案 0 :(得分:5)
在Unix中,您可以在Bourne shell中使用以下命令(即sh
/ bash
):
for f in *_passive.sss; do mv -v $f `basename $f _passive.sss`.sss; done
答案 1 :(得分:1)
这个shell脚本可以解决这个问题:
while read f; do
fp="`echo "$f" | sed -nr 's|(.*)(\.sss)|\1_passive\2| p'`"
if [ -f "$fp" ]; then mv "$fp" "$f"
else echo "file $fp missing" >> missing.log
fi
done<<<"`ls -1 *.sss | grep -v _passive.sss`"
还会将遗失的_passive
个文件报告给missing.log
答案 2 :(得分:1)
这是一个python解决方案:
import os
from glob import glob
# Write out test files.
with open('foo.sss', 'w'): pass
with open('foo_passive.sss', 'w'): pass
with open('bar.sss', 'w'): pass
# Rename files.
files = glob('*.sss')
for filename in files:
if filename.endswith('_passive.sss'): continue
passive_fname = filename.split('.sss')[0] + '_passive.sss'
if passive_fname in files:
os.remove(filename)
os.rename(passive_fname, filename)
else:
print 'no passive: ', filename