重命名文件以获取父文件夹中的名称

时间:2013-01-05 17:32:29

标签: regex windows cygwin

我需要在目录中命名文件,以便它们获取父文件夹的名称,然后递增1。

所以我有

myfolder
-- myfirstfile.txt
-- mysecondfile2.txt

我需要它:

myfolder
--myfolder1.txt
--myfolder2.txt

任何提示?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我只是用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);