Satyajit Rajapurkar
Satyajit Rajapurkar

Reputation: 3

Renaming files in subdirectories using a bash script in linux

I am trying to rename all the files within the subdirectories in my folder. The file structure is as follows:

PQR/
    aaa.txt
    bbb.jpg
    ccc.jif
XYZ/
    aaa.txt
    bbb.jpg
    ccc.jif 
LMN/
    aaa.txt
    bbb.jpg
    ccc.jif

What I want:

PQR/
    PQR_aaa.txt
    PQR_bbb.jpg
    PQR_ccc.jif
XYZ/
    XYZ_aaa.txt
    XYZ_bbb.jpg
    XYZ_ccc.jif 
LMN/
    LMN_aaa.txt
    LMN_bbb.jpg
    LMN_ccc.jif

I am trying to use the following bash script but its giving me all kinds of errors (I am relatively new to shell scripting so bear with me).

#!/bin/bash/
for dirname in */
do
 cd $dirname
 dirnew=${dirname/\///}  #To escape the forward slash
 for file in *.*          #Reading the files in the directory
 do
   mv "$file" "$dirnew"_"$file"
 done
 cd ..
done

Upvotes: 0

Views: 57

Answers (1)

John Kugelman
John Kugelman

Reputation: 361615

$dirnew = ${dirname/\///}

A variable assignment cannot have whitespace around the equals sign, and the lefthand side should not have a $. Also you've got one too many slashes in the substitution.

dirnew=${dirname/\//}

Upvotes: 1

Related Questions