![](/img/trans.png)
[英]Convert all EOL (dos->unix) of all files in a directory and sub-directories recursively without dos2unix
[英]Convert all files of a specified extension within a directory to pdf, recursively for all sub-directories
我正在使用以下代碼(來自此答案 )將當前目錄中的所有CPP文件轉換為名為code.pdf的文件,並且效果很好:
find . -name "*.cpp" -print0 | xargs -0 enscript -Ecpp -MLetter -fCourier8 -o - | ps2pdf - code.pdf
我想將此腳本改進為:
使它成為一個.sh文件,該文件可以帶有指定擴展名的參數,而不必將其硬編碼為CPP;
讓它遞歸運行,訪問當前目錄的所有子目錄;
對於遇到的每個子目錄,將指定擴展名的所有文件轉換為一個名為$ NameOfDirectory $ .PDF的PDF並將其放置在該子目錄中。
首先,如果我理解正確的,你用的是什么,其實是錯誤的- find
將從所有子目錄檢索文件。 為了遞歸工作,僅從當前目錄(我將其命名為do.bash
)中獲取文件:
#!/bin/bash
ext=$1
if ls *.$ext &> /dev/null; then
enscript -Ecpp -MLetter -fCourier8 -o - *.$ext | ps2pdf - $(basename $(pwd)).pdf
fi
for subdir in */; do
if [ "$subdir" == "*/" ]; then break; fi
cd $subdir
/path/to/do.bash $ext
cd ../
done
檢查是為了確保確實存在帶有擴展名的文件或子目錄。 該腳本在當前目錄上運行,並以遞歸方式調用自身-如果您不希望使用完整路徑,則可以將其放在PATH列表中,盡管可以使用完整路徑。
首先,如果我理解正確,則此要求:
對於遇到的每個子目錄,將指定擴展名的所有文件轉換為名為$ NameOfDirectory $ .PDF的單個PDF。
是不明智的。 如果這意味着a/b/c/*.cpp
寫入了./c.pdf
,那么如果您還具有a/d/x/c/*.cpp
,那么您就./c.pdf
,因為這兩個目錄的內容映射到相同的PDF。 這也意味着*.cpp
(即當前目錄中的CPP文件)被./..pdf
為名為./..pdf
的文件。
這樣的事情會根據所需的擴展名命名PDF並將其放在源文件旁邊的每個子目錄中,而不會出現這些問題:
#!/usr/bin/env bash
# USAGE: ext2pdf [<ext> [<root_dir>]]
# DEFAULTS: <ext> = cpp
# <root_dir> = .
ext="${1:-cpp}"
rootdir="${2:-.}"
shopt -s nullglob
find "$rootdir" -type d | while read d; do
# With "nullglob", this loop only runs if any $d/*.$ext files exist
for f in "$d"/*.${ext}; do
out="$d/$ext".pdf
# NOTE: Uncomment the following line instead if you want to risk name collisions
#out="${rootdir}/$(basename "$d")".pdf
enscript -Ecpp -MLetter -fCourier8 -o - "$d"/*.${ext} | ps2pdf - "$out"
break # We only want this to run once
done
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.