Skip to content

Instantly share code, notes, and snippets.

@lopes
Created March 8, 2021 17:12
Show Gist options
  • Save lopes/a0f99e825c30bc4800c7bf9ece3723df to your computer and use it in GitHub Desktop.
Save lopes/a0f99e825c30bc4800c7bf9ece3723df to your computer and use it in GitHub Desktop.
Renames NFe (Brazilian invoices) files in PDF format according to data in the document.
#!/bin/sh
#
# Reads a Brazilian "Nota Fiscal Eletrônica" in PDF format,
# figures out what is it competence (the reference in time
# for that document), and then renames the file using this
# data, like: %Y%m[-COUNT].pdf.
#
# Note: the regex may differ according the format used in
# the PDF file (data disposition), so it should be
# adjusted accordingly.
#
# Requires:
# - pdfgrep
#
# Usage
# nferen.sh nfe.pdf
# for i in nfe-*.pdf; do nferen.sh $i; done
#
# Author.: José Lopes <lopes.id>
# Date...: 2021-03-08
# License: MIT
##
NAME="$1"
COMPETENCE="$(pdfgrep -o \[0-9\]\?\[0-9\]\/\[0-9\]\{4\}\ \ "$NAME")"
MONTH="$(echo $COMPETENCE | cut -d "/" -f1 | awk '{printf "%02d\n", $0;}')"
YEAR="$(echo $COMPETENCE | cut -d "/" -f2)"
NEW_NAME="$YEAR$MONTH.pdf"
COUNT=1
while [ -f "$NEW_NAME" ]; do
NEW_NAME="$YEAR$MONTH-$COUNT.pdf"
((COUNT++))
done
mv -v "$NAME" "$NEW_NAME"
@lopes
Copy link
Author

lopes commented Mar 16, 2021

An alt version using the same "engine", but used to rename PDF files from a course I was taking - PDF files had this pattern "UNIT XX" and file names should result in something like unit-xx.pdf:

NAME="$1"
UNIT="$(pdfgrep -i -o -m 1 "unit [0-9][0-9]" "$NAME" | tr " " "-" | awk '{print tolower($0)}')"
NEW_NAME="$UNIT.pdf"
COUNT=1

while [ -f "$NEW_NAME" ]; do
    NEW_NAME="$UNIT-$COUNT.pdf"
    ((COUNT++))
done
mv -v "$NAME" "$NEW_NAME"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment