0

I have a big pile of pdf's and I would like to batch rename them by content. (They are all searchable). And I'd like to do so using command line interface.

They are all payslips so they have a constant form, and I'd like to rename by date.

Currently they are named: payslip100 .. payslip308

The string for renaming would be the date component in Payment Date: 15/4/2016

I have installed pdfgrep using home-brew and am searching using pdfgrep -HC 15 "Payment Date:" paySlip.pdf

which returns paySlip.pdf:Payment Date: 8/7/2016


I have attached my final working code in a reply.

  • How do you perform search on PDFs? – techraf Jul 20 '16 at 9:45
  • I've just noticed that I can search the pdf's content using mdfind, which will give me the list of files containing a particular string. mdfind annual -onlyin ./ But grep will not output any results from the same search. grep annual *.* – watermelon Jul 20 '16 at 9:50
  • So please update your question with the command you run and its results for a number of files. Then we can add commands to rename the files. – techraf Jul 20 '16 at 9:51
  • This is a long shot. What are the results of- grep --binary-files=text 'Payment Date:' file.pdf? Where file.pdf is a single pdf file that you want to search. – fd0 Jul 20 '16 at 10:25
  • grep --binary-files=text 'Payment Date:' file.pdf does not help. I'm thinking of trying pdftotext which I can apparently install using home-brew. apple.stackexchange.com/questions/155250/…. – watermelon Jul 20 '16 at 10:42
1

After some efforts I have come to a useful result !! sed syntax is quite confusing and I am quite happy to exist in a state where it works without knowing quite why.

#!/bin/bash
for file in *.pdf
do
    # return file name and date in form "Payment Date:   8/7/2016"
    date=$(pdfgrep -C 15 "Payment Date:" "$file")
    echo $date

    # now replace / with - to make naming file easier
    date2=$(echo "$date" | sed 's,/,-,g')
    echo $date2

    # use date string to rename : YYYY-mm-payslip-dd-mm-YYYY.pdf
    new=$(echo "$date2" | sed 's,\Payment Date:\ *\(.*\)-\(.*\)-\(.*\),\3-\2-\payslip-\1-\2-\3.pdf,')
    echo mv "$file" "$new"
done

I used pdfgrep which was installed using homebrew (found on another answer I can't find right now).

I needed to change "/" for file name. Using the forward slash as sed syntax is not necessary, and can be replaced by other characters. Hence using "," instead of "/" https://stackoverflow.com/questions/17379293/replace-forward-slash-with-double-backslash-enclosed-in-double-quotes

I found there were variable spaces in $date which necessitated the ..Payment Date:\ *\...

I added year and month to start of file name for organising purposes.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .