Bash Script to Rename Files in a Directory

Bash Script to Rename Files in a Directory

I am trying to write a script that takes a directory as a command line parameter and iterates over the files in the directory changing their extension to .bu .

I thought this would work but I'm getting the output '.bu' is not a target directory

#!/bin/bash

for  f in $1; do
  mv "$f".* .bu
done
0

4 Answers

#!/bin/bash
cd $1
for f in *; do 
mv  "$f" "${f%.*}.bu"
done

Try that instead (assuming that $1 is a folder):

for f in $1/*; do 
  mv "$f" "$f.bu"
done

Or use the rename utility:

rename -v 's/$/\.bu/' $1/*

Those commands add an extension. If you want to change the existing extension use that:

rename -v 's/\.[^\.]+$/\.bu/' $1/*
5

Taking the KISS approach, I would recommend the following script

#! /bin/bash
cd $1;
rename 's/$/\.bu/' *

This will change working directory to the first parameter and then add a .bu extension to all files. This nullifies the need of for loop.

EDIT:
If you want to change the extension(instead of just adding it), you can try

rename 's/\..*$/\.bu/' *

command instead, in the above script.

$1 within a bash script is a reference to the fist argument passed from the command line, so you're actually trying to process a single folder.

There are answers already about how to solve your problem using pure bash, but I'd like to add that if you need a better filtering of what is being processed you can use find with some options to select the files to be processed:

find <path_to_directory> -maxdepth 1 -type f

*<path_to_directory> = path to the directory

Then loop over the list of files using stdin redirection:

#!/bin/bash

while read file
do
    rename 's/\..*/\.bu/' $file
done <<< $(find $1 -maxdepth 1 -type f)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.