2013-08-21 163 views
1
#!/bin/bash 
#script to loop through directories to merge files 

mydir=/data/ 
files="/data/*" 

for f in $files 
do 
    if[ -d "$f" ] 
    then 
      for ff in $f/* 
      do 
        echo "Processing $ff" 
      done 
    else 
      echo "Processing $f" 
    fi 
done 

我有上面的代碼來瀏覽目錄和子目錄並列出所有文件。我得到的錯誤:語法錯誤附近的意外令牌`然後'腳本遍歷目錄和子目錄到列表文件

我在做什麼錯在這裏?

回答

5
if [ -d "$f" ] 
^

需要有if[之間的空間。如果你沒有空間,bash會認爲你正在執行一個名爲if[的命令。


files="/data/*" 
for f in $files 

也知道這是行不通的。要將通配符擴展存儲到類似的變量中,您需要使用數組。語法是有點多毛......

files=(/data/*) 
for f in "${files[@]}" 

或者你可以寫通配符內聯你的內循環的方式做。這將工作正常。

for f in "$mydir"/* 

對於它的價值,你可以使用find通過的所有文件和子目錄遞歸遞歸。

find /data/ -type f -print0 | while read -d $'\0' file; do 
    echo "Processing $file" 
done 

-type f僅匹配文件。 -print0-d $'\0'結合使用是一種對包含空格,製表符甚至換行符等字符的文件名進行額外處理的方法。在文件名中包含這些字符是合法的,所以我喜歡以能夠處理它們的方式編寫我的腳本。

請注意,這將比子目錄遞歸得更深。它會一路走下去。如果這不是您想要的,請添加-maxdepth 2

+1

謝謝!!這工作! –

3

作爲替代方案,你也許可以代替的東西這整個環路像

# find all files either in /data or /data/subdir 
find /data -type f -maxdepth 2 | while read file; do 
    echo $file; 
end 
+0

我正在使用循環,因爲我只是通過列出文件名來測試我的代碼。我真的必須做一些其他處理,比如通過進入子目錄來合併文件,然後出來,返回到另一個子目錄,再次合併文件等等。感謝您的輸入! –

+0

沒問題。只是想確保你知道! –

+0

我在我的程序中動態創建文件。有沒有辦法動態分配它們?我希望他們的名字匹配我的目錄名稱。 –

0

這裏是一個函數,它你問什麼,你傳遞給它一個文件夾中看到底部func_process_folder_set「/文件夾」的號召。

# --- -------------------------------- --- # 
    # FUNC: Process a folder of files 
    # --- -------------------------------- --- # 
    func_process_folder_set(){ 

     FOLDER="${1}" 

     while read -rd $'\0' file; do 

      fileext=${file##*.} # -- get the .ext of file 
      case ${fileext,,} # -- make ext lowercase for checking in case statement 
      echo "FILE: $file" # -- print the file (always use " " to handle file spaces) 

     done < <(find ${FOLDER} -type f -maxdepth 20 -name '*.*' -print0) 

    } 

    # -- call the function above with this: 
    func_process_folder_set "/some/folder"