2012-09-17 130 views
0

我有一個文件夾「測試」中有20個其他文件夾具有不同的名稱,如A,B ....(實際上它們是人的名字不是A,B .. 。)我想編寫一個shell腳本,轉到像test/A這樣的每個文件夾,並用A [1,2 ..]重命名所有的.c文件,並將它們複製到「test」文件夾中。我開始這樣,但我不知道如何完成它!如何在shell腳本中複製和重命名文件

#!/bin/sh 
for file in `find test/* -name '*.c'`; do mv $file $*; done 

你能幫助我嗎?

回答

0

此代碼應該讓你關閉。我試圖準確地記錄我在做什麼。

它確實依賴BASH和find的GNU版本來處理文件名中的空格。我在.DOC文件的目錄填充中測試了它,所以您還需要更改擴展名。

#!/bin/bash 
V=1 
SRC="." 
DEST="/tmp" 

#The last path we saw -- make it garbage, but not blank. (Or it will break the '[' test command 
LPATH="/////" 
#Let us find the files we want 
find $SRC -iname "*.doc" -print0 | while read -d $'\0' i 
    do 
    echo "We found the file name... $i"; 

    #Now, we rip off the off just the file name. 
    FNAME=$(basename "$i" .doc) 
    echo "And the basename is $FNAME"; 
    #Now we get the last chunk of the directory 
    ZPATH=$(dirname "$i" | awk -F'/' '{ print $NF}') 
    echo "And the last chunk of the path is... $ZPATH" 

    # If we are down a new path, then reset our counter. 
    if [ $LPATH == $ZPATH ]; then 
    V=1 
    fi; 
    LPATH=$ZPATH 

    # Eat the error message 
    mkdir $DEST/$ZPATH 2> /dev/null 
    echo cp \"$i\" \"$DEST/${ZPATH}/${FNAME}${V}\" 
    cp "$i" "$DEST/${ZPATH}/${FNAME}${V}" 
done 
+0

非常感謝您的幫助。 – Sara

0
#!/bin/bash 

## Find folders under test. This assumes you are already where test exists OR give PATH before "test" 
folders="$(find test -maxdepth 1 -type d)" 

## Look into each folder in $folders and find folder[0-9]*.c file n move them to test folder, right? 
for folder in $folders; 
do 
    ##Find folder-named-.c files. 
    leaf_folder="${folder##*/}" 
    folder_named_c_files="$(find $folder -type f -name "*.c" | grep "${leaf_folder}[0-9]")" 

    ## Move these folder_named_c_files to test folder. basename will hold just the file name. 
    ## Don't know as you didn't mention what name the file to rename to, so tweak mv command acc.. 
    for file in $folder_named_c_files; do basename=$file; mv $file test/$basename; done 
done