重命名文件以在父文件夹中取名称



我需要命名目录中的文件,以便它们采用父文件夹的名称,然后增加1。

所以我有

myfolder
-- myfirstfile.txt
-- mysecondfile2.txt

我需要它是:

myfolder
--myfolder1.txt
--myfolder2.txt

提示吗?

sgeorge-mn:stack sgeorge$ pwd
/tmp/stack
sgeorge-mn:stack sgeorge$ ls 
aTMP    bTMP    cTMP    dTMP    eTMP    fTMP    gTMP    hTMP    iTMP    jTMP    kTMP    lTMP    mTMP    nTMP    oTMP    pTMP    qTMP    rTMP    sTMP    tTMP    uTMP    vTMP    wTMP    xTMP    yTMP    zTMP
sgeorge-mn:stack sgeorge$ NUM=1;for i in `ls -1`;do mv $i `pwd`/$i$NUM.txt; ((NUM++)); done
sgeorge-mn:stack sgeorge$ ls
aTMP1.txt   cTMP3.txt   eTMP5.txt   gTMP7.txt   iTMP9.txt   kTMP11.txt  mTMP13.txt  oTMP15.txt  qTMP17.txt  sTMP19.txt  uTMP21.txt  wTMP23.txt  yTMP25.txt
bTMP2.txt   dTMP4.txt   fTMP6.txt   hTMP8.txt   jTMP10.txt  lTMP12.txt  nTMP14.txt  pTMP16.txt  rTMP18.txt  tTMP20.txt  vTMP22.txt  xTMP24.txt  zTMP26.txt

如果文件名中有空格,则相应地更改IFS变量

IFS如何影响:

sgeorge-mn:stack sgeorge$ ls -1
a STACK
b STACK
c STACK
d STACK
e STACK
f STACK

设置IFS'n'前:

sgeorge-mn:stack sgeorge$ for i in `ls -1`; do echo $i ; done
a
STACK
b
STACK
c
STACK
d
STACK
e
STACK
f
STACK

设置IFS'n'后:

sgeorge-mn:stack sgeorge$ TMPIFS=$IFS;IFS='n'; for i in `ls -1`; do echo $i ; done; IFS=$TMPIFS
a STACK
b STACK
c STACK
d STACK
e STACK
f STACK

我只是用python来做这个…

import os
...
def get_files_in_directory(rootDir=rootDirectory):
    for root, dirs, files in os.walk(rootDir, topdown='true'):
        counter = 0;
        for file in files:
            #I only wanted to rename files ending with .mod
            ext = os.path.splitext(file)[-1].lower();
            if (ext == '.mod'):
                # here is how I got the parent folder name 
                folder = os.path.relpath(root, rootDir);
                counter+=1;
                newfilename = folder + '_' + counter + ".mod";
                os.rename(root + '\' +  file, root + '\' + newfilename);

最新更新