2013-01-05 51 views
-1

我需要讓他們把父文件夾的名字來命名文件的目錄,然後通過1重命名文件取的名字在父文件夾的

遞增所以我有

myfolder 
-- myfirstfile.txt 
-- mysecondfile2.txt 

我需要它是:

myfolder 
--myfolder1.txt 
--myfolder2.txt 

任何提示?

+0

你爲什麼要標記這個'regex'? –

+0

以爲我可能能夠使用正則表達式進行重命名。我不知道。 – dublintech

回答

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$ 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 
+0

ar eyou從bash shell運行?我得到:mv:未知選項 - l。當我刪除選項,只是嘗試LS,我得到:mv:不能stat'ls':沒有這樣的文件或目錄 – dublintech

+0

是的,在Ubuntu上bash。 – Suku

+0

問題我有我的空間是在我的文件名。有任何想法嗎? – dublintech

0

我只是用蟒蛇做日:

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'設置完成後是...

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);