linux - 将目录内指定扩展名的所有文件转换为pdf,对所有子目录递归

标签 linux bash find xargs enscript

我正在使用以下代码(来自 this answer)将当前目录中的所有 CPP 文件转换为名为 code.pdf 的文件,并且运行良好:

find . -name "*.cpp" -print0 | xargs -0 enscript -Ecpp -MLetter -fCourier8 -o - | ps2pdf - code.pdf

我想将此脚本改进为:

  1. 把它变成一个 .sh 文件,可以带一个参数指定 扩展而不是将其硬编码为 CPP;

  2. 让它递归运行,访问当前目录的所有子目录;

  3. 对于遇到的每个子目录,将指定扩展名的所有文件转换为名为 $NameOfDirectory$.PDF 的单个 PDF 并放置在该子目录中;

    <

最佳答案

首先,如果我没有理解错的话,这个需求:

For each subdirectory encountered, convert all files of the specified extension to a single PDF that is named $NameOfDirectory$.PDF

是不明智的。如果这意味着,比方说,a/b/c/*.cpp 被写入 ./c.pdf,那么如果您还有 ,那您就完蛋了a/d/x/c/*.cpp,因为两个目录的内容映射到同一个 PDF。这也意味着 *.cpp(即 current 目录中的 CPP 文件)被写入名为 ./..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

关于linux - 将目录内指定扩展名的所有文件转换为pdf,对所有子目录递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632016/

相关文章:

c - 我如何知道在 Linux 上使用哪个串口?

android - Cordova 在我的路径中找不到 ANDROID_HOME 或 android,尽管它们在那里

regex - 如何使用 grep 的正则表达式从文件中提取 base64 文本

bash - 将文件的每一行作为参数传递给命令?

bash - 删除所有早于 X 天的文件,但至少保留 Y 最年轻的文件

linux - 如何从远程机器获取文件夹到本地机器?

regex - Perl 的\K in bash 函数

linux - 使用 '&' 和 'wait' 时后台进程不会死亡

regex - 在 Linux 中使用非消耗匹配查找正则表达式

vba - 查找日期是否存在于单元格范围中(Excel VBA)