Karim Bn Abdlaziz
Karim Bn Abdlaziz

Reputation: 57

Rename only unique files

How to rename only unique files by removing "1" from file name and keep duplicated name files?

Input:

-english_1.pdf  
-english_2.pdf  
-english_3.pdf  
-mathematics_1.pdf  
-theology_1.pdf  
-economics_1.pdf  
-economics_2.pdf

How can I remove the 1 from mathematics_1.pdf and theology_1.pdf with , or similar?

Desired output:

-english_1.pdf  
-english_2.pdf  
-english_3.pdf  
-mathematics.pdf  
-theology.pdf  
-economics_1.pdf  
-economics_2.pdf

I tried:

rename -n  's/1//' *.pdf

but it removes all the 1

Upvotes: 0

Views: 77

Answers (1)

kvantour
kvantour

Reputation: 26471

A safe bet might be the following method:

for file in *_1.pdf; do
   [ -f "${file/_1.pdf/_2.pdf}" ] || mv "${file}" "${file/_1.pdf/.pdf}"
done

What this does is the following:

  • for file in *_1.pdf; do ... done: make a loop over all files which match the glob pattern *_1.pdf. So this matches all files that look like prefix_1.pdf
  • [ -f "${file/_1.pdf/_2.pdf}" ]: The first thing we do in the loop is to verify if there exists a similar file with name prefix_2.pdf. We obtain this filename with the parameter expansion

    ${parameter/pattern/string}: Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion, Parameter is expanded and the longest match of pattern against its value is replaced with string.

    source: man bash

    The test command, written as [ -f filename ] checks if a file with filename exists. See man test for more information.

  • If the above test is successful, we do nothing. If the above test is unsuccessful, we rename the original file using mv "${file}" "${file/_1.pdf/.pdf}". This conditional combination is achieved using on OR-list:

    An OR list has the form command1 || command2. command2 is executed if, and only if, command1 returns a non-zero exit status.

    source: man bash

I'm assuming here that a file prefix_2.pdf must exist if prefix_3.pdf exists.

You can validate the above by adding echo before the mv command.

Upvotes: 5

Related Questions