2013-09-30 32 views
0

(我在Bash環境中,Cygwin在Windows機器上,使用awk,sed,grep,perl等) 我想要將最後一個文件夾名稱添加到文件名中,緊接在最後一個下劃線(_)後面跟着數字,或者在文件名中沒有數字的末尾。BASH:如何在文件名中間重命名大量文件insertnig文件夾名稱

這裏(數百所需要的文件,以進行重組)的是我有一個例子:

./aaa/A/C_17x17.p 
./aaa/A/C_32x32.p 
./aaa/A/C.p 
./aaa/B/C_12x12.p 
./aaa/B/C_4x4.p 
./aaa/B/C_A_3x3.p 
./aaa/B/C_X_91x91.p 
./aaa/G/C_6x6.p 
./aaa/G/C_7x7.p 
./aaa/G/C_A_113x113.p 
./aaa/G/C_A_8x8.p 
./aaa/G/C_B.p 
./aab/... 

我想改名這樣所有thses文件:

./aaa/C_A_17x17.p 
./aaa/C_A_32x32.p 
./aaa/C_A.p 
./aaa/C_B_12x12.p 
./aaa/C_B_4x4.p 
./aaa/C_A_B_3x3.p 
./aaa/C_X_B_91x91.p 
./aaa/C_G_6x6.p 
./aaa/C_G_7x7.p 
./aaa/C_A_G_113x113.p 
./aaa/C_A_G_8x8.p 
./aaa/C_B_G.p 
./aab/... 

我試過很多bash for循環sed和最後一個是以下內容:

IFS=$'\n' 
for ofic in `find * -type d -name 'A'`; do 
    fic=`echo $ofic|sed -e 's/\/A$//'` 
    for ftr in `ls -b $ofic | grep -E '.png$'`; do 
    nfi=`echo $ftr|sed -e 's/(_\d+[x]\d+)?/_A\1/'` 
    echo mv \"$ofic/$ftr\" \"$fic/$nfi\" 
    done 
done 

但還沒有成功... T他的\1沒有插入$nfi ... 這是我試過的最後一個,只在1個文件夾(這是一個巨大的文件夾集合的子文件夾)上工作,經過60多分鐘的不成功試驗後,我在這裏和你們一起。

+2

您是否安裝過'rename'? –

+0

我這樣做,謝謝一堆,我會看看那個軌道! – menssana

回答

1

我修改腳本,以便它適用於所有的例子。

IFS=$'\n' 
for ofic in ???/?; do 
    IFS=/ read fic fia <<<$ofic 
    for ftr in `ls -b $ofic | grep -E '\.p.*$'`; do 
    nfi=`echo $ftr|sed -e "s/_[0-9]*x[0-9]*/_$fia&/;t;s/\./_$fia./"` 
    echo mv \"$ofic/$ftr\" \"$fic/$nfi\" 
    done 
done 
1
# it's easier to change to here first 
cd aaa 
# process every file 
for f in $(find . -type f); do 
    # strips everything after the first/so this is our foldername 
    foldername=${f/\/*/} 
    # creates the new filename from substrings of the 
    # original filename concatenated to the foldername 
    newfilename=".${f:1:3}${foldername}_${f:4}" 
    # if you are satisfied with the output, just leave out the `echo` 
    # from below 
    echo mv ${f} ${newfilename} 
done 

可能適合你。

See here in action.(略作修改,如ideone.com處理STDIN/find diferently ...)

+0

謝謝,但根本沒有,在這裏,文件夾和文件名有隨機長度... – menssana

+0

你試過了嗎? Chechk的行動鏈接也... 你能請示例一個真實的例子,你的例子上述解決方案的作品? –

相關問題