更新されたPDFを比較するBashスクリプト

更新されたPDFを比較するBashスクリプト

フォルダ内の各ファイルにはpdf3つの関連ファイルがあります。

original.pdf
original.txt
original_roc_mrc.pdf
original_roc_mrc_updated.pdf

これで、次のようなスクリプトが必要です。

  1. ページ数が同じであるoriginal.pdfことを確認してください。original_roc_mrc_updated.pdf

  2. original_roc_mrc.pdfサイズが最大20%大きいことを確認してください。original_roc_mrc_updated.pdf

  3. 以前の内容がtrueの場合、 original.pdfおよびoriginal.txtを削除しますoriginal_roc_mrc.pdf。 1) または 2) が偽の場合は、「pack」に対して何もしないでください。

ベストアンサー1

pdftkがインストールされておらず、必要なすべてのJavaエントリをインストールしたくないので、ここにpoppler-utilのpdfinfoを使用してページ数を取得し、残りのタスクを実行するスクリプトがあります。

#!/usr/bin/env bash

# function to get filesize
filesize() {
    stat -c '%s' "$1"
}

# function to get number of pages
numpages() {
    pdfinfo "$1" | sed -n 's/^Pages:\s*\([0-9]*\)\s*/\1/p'
}

# get number of pages for these two files
pages1="$(numpages original.pdf)"
pages2="$(numpages original_roc_mrc_updated.pdf)"

# get filesizes of these two files
size1="$(filesize original_roc_mrc_updated.pdf)"
size2="$(filesize original_roc_mrc.pdf)"

# determine the maxfilesize to be 20% larger or less
# 120% = the original size plus 1/5th of original size
maxsize=$(( size1 + size1/5 ))

# see if pages1=pages2 and size2 <= maxsize
if [[ pages1 -eq pages2 ]] &&
    [[ size2 -le maxsize ]] ; then
    rm original.pdf original.txt original_roc_mrc.pdf
fi

何らかの理由でpdftkを使用したい場合は、その機能を次のように置き換えることができます。

numpages() {
    pdftk "$1" dump_data | grep NumberOfPages | awk '{print $2}'
}

名前を含まないフォルダ内のすべての.pdfに名前を適用するには、mrc次のループを使用できます(質問編集で同じコードの大部分を使用)。

#!/usr/bin/env bash

# function to get filesize
filesize() {
    stat -c '%s' "$1"
}

# function to get number of pages
numpages() {
    pdfinfo "$1" | sed -n 's/^Pages:\s*\([0-9]*\)\s*/\1/p'
}


for filename in *.pdf ; do

    # skip files with "mrc" in their name
    if [[ "$filename" =~ "mrc" ]] ; then
        continue
    fi

    # determine common part of filenames
    commonname="${filename%.pdf}"
    
    # get number of pages for these two files
    pages1="$(numpages "$filename")"
    pages2="$(numpages "${commonname}_roc_mrc_updated.pdf")"

    # get filesizes of these two files
    size1="$(filesize "${commonname}_roc_mrc_updated.pdf")"
    size2="$(filesize "${commonname}_roc_mrc.pdf")"

    # determine the maxfilesize to be 20% larger or less
    # 120% = the original size plus 1/5th of original size
    maxsize=$(( size1 + size1/5 ))

    if [[ pages1 -eq pages2 ]] &&
        [[ size2 -le maxsize ]] ; then
        rm "$filename" "${commonname}.txt" "${commonname}_roc_mrc.pdf"
    fi
done

おすすめ記事