Search code examples
linuxunixscriptingjpeg

How to combine Linux find, convert and copy commands into one command


I have the following cmd that fetches all .pdf files with an STP pattern in the filename and places them into a folder:

find /home/OurFiles/Images/ -name '*.pdf' |grep "STP*" | xargs cp -t /home/OurFiles/ImageConvert/STP/

I have another cmd that converts pdf to jpg.

find /home/OurFiles/ImageConvert/STP/ -type f -name '*.pdf' -print0 |
  while IFS= read -r -d '' file
    do convert -verbose -density 500 -resize 800 "${file}" "${file%.*}.jpg"

    done

Is it possible to combine these commands into one? Also, I would like pre-pend a prefix onto the converted image file name in the single command, if possible. Example: STP_OCTOBER.jpg to MSP-STP_OCTOBER.jpg. Any feedback is much appreciated.


Solution

  • find /home/OurFiles/Images/ -type f -name '*STP*.pdf' -exec sh -c '
      destination=$1; shift        # get the first argument
      for file do                  # loop over the remaining arguments
        fname=${file##*/}          # get the filename part
        cp "$file" "$destination" && 
          convert -verbose -density 500 -resize 800 "$destination/$fname" "$destination/MSP-${fname%pdf}jpg"
      done
    ' sh /home/OurFiles/ImageConvert/STP {} +
    

    You could pass the destination directory and all PDFs found to find's -exec option to execute a small script.
    The script removes the first argument and saves it to variable destination and then loops over the given PDF paths. For each filepath, extract the filename, copy the file to the destination directory and run the convert command if the copy operation was successful.