这段代码如何变得更短?

这段代码如何变得更短?

请告诉我如何使这段代码变得更短:

find /home/peace/* -iname "*.pdf" -exec pdfgrep -i yello {} \; -exec cp {} /home/peace/Desktop/yello \;
find /home/peace/* -iname "*.pdf" -exec pdfgrep -i green {} \; -exec cp {} /home/peace/Desktop/green \;
find /home/peace/* -iname "*.pdf" -exec pdfgrep -i blue {} \; -exec cp {} /home/peace/Desktop/blue \;
find /home/peace/* -iname "*.pdf" -exec pdfgrep -i grey {} \; -exec cp {} /home/peace/Desktop/grey \;
find /home/peace/* -iname "*.pdf" -exec pdfgrep -i black {} \; -exec cp {} /home/peace/Desktop/black \;
find /home/peace/* -iname "*.pdf" -exec pdfgrep -i white {} \; -exec cp {} /home/peace/Desktop/white \;

答案1

zsh

#! /bin/zsh -
cd /home/peace || exit
set -o extendedglob # for (#i)
pdf=(*.(#i)pdf(.ND)) # all pdf files case insensitive, including hidden ones
                     # in the current directory, only considering regular files.
colors=(yello green blue grey black white)

(($#pdf)) || exit 0 # exit with success if there's no pdf file (job already done)

ret=0
for color ($colors) {
  files=(${(0)"$(pdfgrep -ilZe $color -- $pdf)"}) # all files containing the color
                                                  # using NUL-delimited records
  if (($#files)) { # some files were found
    mv -i -- $files Desktop/$color/ || ret=$? # move them, record failures
    pdf=(${pdf:|files}) # remove the files from the list as we've moved them
  }
}
exit $ret

这可以最大限度地减少目录的调用次数和读取pdfgrep次数。/home/peace

答案2

我可以看到一些改进的空间。

  • find的第一个参数是目录,而不是末尾带有“*”的路径;

  • find 确实在子目录内搜索,因此您希望限制“find”不在子目录中搜索(find 参数“-maxdepth 1”);

  • 将查找结果限制为文件,因为如果您有名为“something.pdf”的目录,您可能不喜欢结果(查找参数“-type f”);

  • cp 第二个参数 /home/peace/Desktop/yello 是结果文件名?但是如果 pdfgrep 可以在几个 pdf 文件中找到“yello”,哪一个是正确的结果呢?如果“/home/peace/Desktop/yello”是一个目录,则需要在末尾添加“/”。所以我认为这是我们放置结果文件的目录。

那么我们开始吧:

find /home/peace/ -maxdepth 1 -type f -iname "*.pdf" -exec sh -c '
  for f do
    for i in yello green blue grey black white; do
      pdfgrep -iqe "$i" "$f" &&
        cp -f "$f" "/home/peace/Desktop/$i/"
    done
  done' sh {} + 

我们还可以添加检查结果目录是否存在。

相关内容