-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoi-rename
executable file
·59 lines (47 loc) · 2.28 KB
/
doi-rename
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/sh
# Rename a PDF according to its metadata
# The GPLv3 License (GPLv3)
#
# Copyright (c) 2024 Ivan Boikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
if [ -z "$1" ]; then printf "Usage: doi-rename [PDF]...\n\nRename article PDF according to its metadata.\n" && exit ; fi
RED='\033[0;31m'
NC='\033[0m' # No Color
while [ "$#" -ne 0 ]; do
if [ ! -f "$1" ]; then printf "${RED}%s${NC} not found\n" "$1" && shift && continue ; fi
meta="$(pdfinfo -custom "$1")"
# each author (Name Surname) per line
authors="$(echo "$meta" | grep Author | cut -d: -f2 | sed -e 's/, /\n/g' -e 's/ and /\n/g' -e 's/^[ \t]*//;s/[ \t]*$//')"
firstauthor="$(echo "$authors" | head -n1 | rev | cut -d' ' -f1 | rev)"
# some might remember the head of the lab better
lastauthor="$(echo "$authors" | tail -n1 | rev | cut -d' ' -f1 | rev)"
year="$(echo "$meta" | grep Subject | grep -Po ', (\d{4}), ' | cut -d, -f2 | xargs)"
title="$(echo "$meta" | grep Title | cut -d: -f2- | xargs | tr '/' '-')"
# trim title length, 128 should suffice in most cases
title="$(echo "$title" | cut -c -128)"
# sanity check -- add more if needed!
if [ -z "$firstauthor" ] || [ -z "$title" ] || ! [ "$year" -eq 0 -o "$year" -ne 0 ] >/dev/null 2>&1 ; then
printf "${RED}%s${NC} has incorrect metadata, use doi-repair first\n" "$1"
printf "\tFirst author: %s\n\tYear: %s\n\tTitle: %s\n" "$firstauthor" "$year" "$title"
shift && continue
fi
# personal preference: bibtex-style ref first...
fname="$firstauthor$year"
[ ! "$lastauthor" = "$firstauthor" ] && fname="$fname-$lastauthor"
# and kebab-case with lower-case symbols
fname="$(echo "$fname-$title.pdf" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')"
mv -n "$1" "$(dirname "$1")/$fname"
shift
done