1

I have thousands of PDF files named in the format

Author Year Title of the book

The first two spaces are relevant: they make a break between the Author, the year and the title. The title could contain a number of space. I am looking for a script to write the author to the author meta field in the PDF; the Title to the title, and the year to the year metadata. Exiftool seems the most promising of all the tools I looked at.

Can you guys help me?

1 Answer 1

0

Some EXIF manipulation tools have a built-in way to rename files based on EXIF data, but I don't know of one that can do it the other way round. So let the shell call the program with the right parts of the file names. Here's a script that processes just one file (pass the name as the sole argument of the script).

#!/bin/sh
title=${1##*/}
author=${title%% *}; title=${title#* }
year=${title%% *}; title=${title#* }
exiftool -Author="$author" -Title="$title" -CreateDate="$year" "$1"

Explanation: I use parameter expansion constructs to perform some basic string processing: put the base name (after the last /) into title; put the part up to the first space into author and remove that from title; repeat with the year.

To process all the files in a directory, put that code in a loop.

#!/bin/sh
for filename in *\ *\ *.pdf; do
  title=${filename##*/}
  author=${title%% *}; title=${title#* }
  year=${title%% *}; title=${title#* }
  exiftool -Author="$author" -Title="$title" -CreateDate="$year" "$filename"
done

To process all the files in a directory and its subdirectories recursively, use find.

find /path/to/top/directory -name '* * *.pdf' -type f -exec sh -c '
  for filename do
    …
  done
' _ {} +
6
  • Thank you Gilles. but, I am sorry I am not able to run it properly. I have no idea how these programs work. So, what I want is to put the script in Hazel (a mac application which automatically runs in the background. It can run Shell Scripts. It seems to require $1 as a means to feed the files to the scripts). I have tried replacing $filename by $1, with no luck. Yes, all of my files are stored in a folder. The reason I want to run it in Hazel is because the application can run the script in the future as I add more files to the folder.
    – Dellu
    Feb 27, 2016 at 5:38
  • @user3015087 I've turned the first snippet into a full script. Feb 27, 2016 at 11:46
  • Yes, it is working now: almost there. The only issue is the Year is included into the Title field.
    – Dellu
    Feb 28, 2016 at 17:38
  • @Dellu That was a copy-paste error, I fixed it. Feb 28, 2016 at 17:42
  • Hello, I am back after a while. This script is serving me well. So grateful!. But, I just noticed that the Title includes the file extension. is it possible to exclude the file extension?
    – Dellu
    Mar 29, 2016 at 19:42

You must log in to answer this question.

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