-1

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

所以我有

myfolder
-- myfirstfile.txt
-- mysecondfile2.txt

我需要它是:

myfolder
--myfolder1.txt
--myfolder2.txt

有小费吗?

4

2 回答 2

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
于 2013-01-05T17:49:23.733 回答
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);
于 2013-01-05T19:31:39.270 回答