2012-02-07 63 views
1

我有一個子目錄和名稱以類似於子目錄的字符串開頭的文件的目錄;例如在腳本中將文件移動到具有相似名稱的目錄

bar/ 
    foo-1/ (dir) 
    foo-1-001.txt 
    foo-1-002.txt 
    foo-1-003.txt 
    foo-2/ (dir) 
    foo-2-001.txt 
    foo-2-002.txt 
    foo-2-003.txt 
    foo-3/ (dir) 
    foo-3-001.txt 
    foo-3-002.txt 
    foo-3-003.txt 


所有文件目前正處於同一水平。我想用腳本將相應的.txt文件移動到它們類似名稱的目錄中(在我目前的情況下,大於9500)。

我寫了以下內容,但我錯過了一些內容,因爲我無法移動文件。

#!/bin/sh 

# directory basename processing for derivatives 
# create directory list in a text file 
find ./ -type d > directoryList.txt 


# setup while loop for moving text files around 
FILE="directoryList.txt" 
exec 3<&0 
exec 0<$FILE 
while read line 
do 
    echo "This is a directory:`basename $line`" 
filemoves=`find ./ -type f -name '*.txt' \! -name 'directoryList.txt' | sed 's|-[0-9]\{3\}\.txt$||g'` 
if [ "`basename $filemoves`" == "$line" ] 
    then 
    cp $filemoves $line/  
    echo "copied $filemoves to $line" 
fi 
done 
exec 0<&3 

事情似乎工作正常,直到我得到if。我正在處理大量的* nix,所以我必須小心我所用的參數(RHEL,FreeBSD,也可能是Mac OS X)。

回答

3

假設文件確實符合上述模式(在最後一個短劃線之前的所有內容都是目錄名稱)應該這樣做:

for thefile in *.txt ; do mv -v $thefile ${thefile%-*}; done 

,如果告訴你是命令行過長(擴大* .TXT到4900個文件是很多)試試這個:

find . -name '*.txt' | while read thefile ; do mv -v $thefile ${thefile%-*} ; done 
+1

+1使用參數擴展。我會給你+2,如果我可以也不使用'ls' – SiegeX 2012-02-07 03:41:05

+0

Ry4an - 非常感謝。 – CanOfBees 2012-02-07 12:34:16

+0

嘿,謝謝@SiegeX。我喜歡花哨的bash參數擴展的東西,並且我花了10年的時間來找到我可以使用它們的地方,而不用去查看它們(很多)。 – 2012-02-07 14:20:12

0

我不是shell腳本專家,但我知道在很多shell中(根據此頁面上的網址:http://www.vectorsite.net/tsshell.html這包括SH),字符串比較是使用「=」運算符完成的,而不是「 ==」。

[「$ shvar」=「fox」]字符串比較,如果匹配則返回true。

-1

[代碼塊移除]

原因1.用於ls代替通配符

原因2.用於mv $VAR1 $VAR2式移動而不引用變量

+0

不解析'ls',使用水珠來代替。閱讀[此鏈接](http://mywiki.wooledge.org/ParsingLs)爲什麼解析'ls'極不鼓勵 – SiegeX 2012-02-07 03:40:16

相關問題