简体   繁体   中英

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
$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/\//}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM