Rename all ".pdf" files to "_0.pdf" [duplicate]

Solution 1:

A simple way would be to use the mmv command:

mmv '*.pdf' '#1_0.pdf'

You might need to install it first (available in the Universe repository):

sudo apt-get install mmv

Solution 2:

With rename (prename):

rename -n 's/\.pdf$/_0$&/' *.pdf
  • \.pdf$ matches .pdf at the end of the filename
  • in the replacement, the match is prepended by _0: _0$&
  • drop -n for actual action

With bash parameter expansion:

for f in *.pdf; do pre="${f%.pdf}"; echo mv -- "$f" "${pre}_0.pdf"; done
  • pre="${f%.pdf}" saves the portion of the filename before .pdf as variable pre

  • while mv-ing _0.pdf is appended to $pre: ${pre}_0.pdf

  • drop echo for actual action


Example:

% rename -n 's/\.pdf$/_0$&/' *.pdf
rename(egg.pdf, egg_0.pdf)
rename(spam.pdf, spam_0.pdf)

% for f in *.pdf; do pre="${f%.pdf}"; echo mv -- "$f" "${pre}_0.pdf"; done
mv -- egg.pdf egg_0.pdf
mv -- spam.pdf spam_0.pdf

Solution 3:

Do you want to rename or copy?

To rename, you can use emacs:

  1. Open the parent directory as a dired buffer
  2. Type M-x wdired-change-to-wdired-mode
  3. Use M-x query-replace to replace '.pdf' with '_0.pdf'
  4. Type C-x C-s to save the buffer

Solution 4:

Do you want to rename or copy the files? For both, you can simply use a for loop and mv (move, also renames) or cp (copy):

for i in *.pdf; do mv "$i" "${i/%.pdf/_0.pdf}"; done

or rather

for i in *.pdf; do cp "$i" "${i/%.pdf/_0.pdf}"; done

The quotation marks are only needed if (one of) your files contains spaces.

Quick explanation: ${i/%.pdf/_0.pdf} takes variable i and substitutes “.pdf” by “_0.pdf” if it is found at the end of the string (hence %). Read more about bash's amazing superpowers here.