【问题标题】:Tell if a file is PDF in bash在 bash 中判断文件是否为 PDF
【发布时间】:2013-04-22 16:58:35
【问题描述】:

我需要编写一个 bash 脚本来判断文件是否为 pdf 文件。但是,我不能简单地使用文件名或扩展名。

例如:

test.pdf.encrypt - 不会打开,因为文件本身已加密并且文件属于计算机无法识别的未知类型。

test.pdf.decrypt - 即使扩展名为 .decrypt 也会打开

由于查看扩展名无济于事,并且加密和解密文件的名称中间都有 .pdf,有没有办法让系统测试并查看文件是否可以用 pdf 阅读器读取?

我只需要可以输入到 bash 中的 if 语句中的命令。

if [this file is a working pdf file]; do
   echo "$file is a working pdf file."
fi

【问题讨论】:

    标签: bash pdf file-type


    【解决方案1】:

    另一种选择是在文件上使用file

    type="$(file -b $file)"
    if [ "${type%%,*}" == "PDF document" ]; then
      echo "$file is a PDF file."
    fi
    

    【讨论】:

      【解决方案2】:

      每个 PDF 文件都以 %PDF 开头。您可以比较指定文件的前 4 个字符,以确保它是 PDF。

      FILE="/Users/Tim/Documents/My File.pdf"
      if [ $(head -c 4 "$FILE") = "%PDF" ]; then
          echo "It's a PDF!"
      fi
      

      【讨论】:

        【解决方案3】:

        在 Linux 和 Solaris 上,file 命令将识别文件类型;具体来说,PDF 文档是众多类型中的一种。

        file filename.xxx | grep -q 'PDF' && echo 'is pdf file'  || echo 'is not pdf'
        

        无论文件扩展名如何。

        【讨论】:

          【解决方案4】:

          file 命令说明文件的类型与扩展名无关。

            $ file Confirmation.pdf 
            Confirmation.pdf: PDF document, version 1.5
          

          【讨论】:

            猜你喜欢
            • 2011-09-05
            • 1970-01-01
            • 1970-01-01
            • 2015-05-03
            • 2013-03-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多