Wednesday, February 7, 2024

[SOLVED] Remove Day Names from filenames with Bash

Issue

I'm trying to create a small Bash script to remove Day Names from PDF file names. For example, I want to rename:

newspaper20240204-sunday_01.pdf
newspaper20240204-sunday_02.pdf
newspaper20240204-sunday_03.pdf
newspaper20240204-sunday_04.pdf
newspaper20240204-sunday_05.pdf
newspaper20240205-monday_01.pdf
newspaper20240205-monday_02.pdf
newspaper20240205-monday_03.pdf
newspaper20240205-monday_04.pdf
newspaper20240205-monday_05.pdf

to

newspaper20240204_01.pdf
newspaper20240204_02.pdf
newspaper20240204_03.pdf
newspaper20240204_04.pdf
newspaper20240204_05.pdf
newspaper20240205_01.pdf
newspaper20240205_02.pdf
newspaper20240205_03.pdf
newspaper20240205_04.pdf
newspaper20240205_05.pdf

I'm new to Bash, so be gentle :] Thank you for any help.


Solution

If the scheme is always something-dayofweek_num.pdf -> something_num.pdf you can try:

for f in *-*_*.pdf; do mv "$f" "${f%-*}_${f##*_}"; done

Explanation: ${f%-*} is one of the many parameter substitutions. It expands as the value of bash variable f with the final part from the last - removed. ${f##*_} is another that expands as the value of bash variable f with the longest prefix, up to the last _, removed.



Answered By - Renaud Pacalet
Answer Checked By - Clifford M. (WPSolving Volunteer)