簡體   English   中英

Bash腳本幫助,包括用於處理文件的子目錄

[英]Bash script help, include sub-directories for processing files

我絕對不是腳本專家。 我有一個處理一些文件的腳本,但我不知道如何針對具有許多子目錄和數千個文件的目錄中的所有文件運行此腳本。 基本上,我想使用此腳本並將其運行在名為2011的目錄中,並使其處理每個子文件夾中的每個文件。

#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done

以下腳本將遞歸到./userfiles下的每個目錄, ./userfiles所有文件進行處理,即使文件名中帶有空格(或其他有害字符)。

同樣,您編寫腳本的方式make將作為其最后一個參數傳遞給文件名,該文件名將出現在磁盤上並附加.html 例如,文件./userfiles/subdir/foobar.txt將被傳遞到作出 ./userfiles/subdir/foobar.txt.html 如果這不是您想要的,請相應地調整${file}.html

另外,如果您希望find 僅對.html結尾的文件起作用,則可以在路徑名之后的任何位置,將-name "*.html"選項附加到find命令。

#!/bin/bash

topLevelDir="./userfiles"

while IFS= read -r -d $'\0' file; do
    echo 
    echo 
    echo "Processing File $file ...."
    echo 
    echo 
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar "${file}".html
    echo  
    echo  
    echo "File $file.html Generated"
done < <(find "$topLevelDir" -type f -print0)

這是一個執行您所要求的功能的函數,您將文件夾傳遞給它,請參見底部的調用func_process_folder_set“ / folder”。

    # --- -------------------------------- --- #
    # 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"

嘗試使用find命令獲取所有文件和目錄的列表

不確定腳本的作用是什么,但是為了從當前文件夾開始為樹中的每個文件運行腳本,可以使用:

find . -exec yourscript.sh {} \;

由於您的腳本已經可以理解文件擴展的一個級別,因此在包含./userfiles目錄的每個目錄上運行該腳本都將變得快速而簡單。

$ find . -type d -a -name userfiles -a -exec sh /whatever/myscript {}/.. \;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM