bash loops and renaming files

Andreas is a RHEL Sysadmin working in his home directory in bash on his RHEL server. His home directory: /home/andreas/

His home directory contains 10 files in alphabetical order:

applications.pdf

bonds.pdf

charges.pdf

deliveries.pdf

enhancements.pdf

free_items.pdf

generic_items.pdf

hotel_loads.pdf

island_resources.pdf

junk_items.pdf

He wants to prepend a two digit number to the beginning of each file: applications.pdf will be renamed 01_applications.pdf, and junk_items.pdf will be renamed 10_junk_items.pdf. Please generate all of the commands that Andreas will need to run to rename all ten files. Please use a bash shell loop, if possible.

Certainly! Andreas can use a bash loop to prepend a two-digit number to each file in his home directory. Here's how he can do it:

#!/bin/bash

cd /home/andreas/  # Move to Andreas' home directory

count=1

for file in *.pdf; do
    new_name=$(printf "%02d_%s" "$count" "$file")
    mv "$file" "$new_name"
    ((count++))
done

Save this script in a file (e.g., rename_files.sh), make it executable using chmod +x rename_files.sh, and then run it with ./rename_files.sh in the terminal. This script will loop through all PDF files in Andreas' home directory and rename them with a two-digit number prefix followed by an underscore.

Please simulate the output for his 10 files.

$ ./rename_files.sh
Renaming applications.pdf to 01_applications.pdf
Renaming bonds.pdf to 02_bonds.pdf
Renaming charges.pdf to 03_charges.pdf
Renaming deliveries.pdf to 04_deliveries.pdf
Renaming enhancements.pdf to 05_enhancements.pdf
Renaming free_items.pdf to 06_free_items.pdf
Renaming generic_items.pdf to 07_generic_items.pdf
Renaming hotel_loads.pdf to 08_hotel_loads.pdf
Renaming island_resources.pdf to 09_island_resources.pdf
Renaming junk_items.pdf to 10_junk_items.pdf

Please note that this is a simulated output, and the actual output might vary depending on your system configuration and the specific files in Andreas' directory. The script provided earlier should work to rename the files as described.

You should also read: