0

Inside a folder I have a file structure, the files have all a name whose format

name-randomstring.extension

eg

./dir1/aaa-5h34jk5hk.js
./dir2/bbb-5yh45uh9h.css
./dir3/ccc-uiero6tio.js
./dir3/ddd-7y8fygfre.css
. . .

with a script I would like to rename them recursively; so to eliminate the -randomstring from every file

./dir1/aaa.js
./dir2/bbb.css
./dir3/ccc.js
./dir3/ddd.css
. . .
Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44
Simone Bonelli
  • 411
  • 1
  • 5
  • 18

2 Answers2

0

if you do not mind using Perl then you can do anything you like.

for example for renaming all files with this structure:

dir > find .
.
./00_file.txt
./01_file.txt
./02_file.txt
./dir1
./dir1/00_file.txt
./dir1/01_file.txt
./dir1/02_file.txt
./dir2
./dir2/00_file.txt
./dir2/01_file.txt
./dir2/02_file.txt
./dir3
./dir3/00_file.txt
./dir3/01_file.txt
./dir3/02_file.txt   
./find.log

then save your list in a file like: find.log now you can use Perl

dir > perl -lne '-f && ($old=$_) && s/file/ABCD/g && print "$old => $_"' find.log
./00_file.txt => ./00_ABCD.txt
./01_file.txt => ./01_ABCD.txt
./02_file.txt => ./02_ABCD.txt
./dir1/00_file.txt => ./dir1/00_ABCD.txt
./dir1/01_file.txt => ./dir1/01_ABCD.txt
./dir1/02_file.txt => ./dir1/02_ABCD.txt
./dir2/00_file.txt => ./dir2/00_ABCD.txt
./dir2/01_file.txt => ./dir2/01_ABCD.txt
./dir2/02_file.txt => ./dir2/02_ABCD.txt
./dir3/00_file.txt => ./dir3/00_ABCD.txt
./dir3/01_file.txt => ./dir3/01_ABCD.txt
./dir3/02_file.txt => ./dir3/02_ABCD.txt 

how it works?

  1. read the file
  2. let only file; not directory or other stuffs with: -f
  3. then save the old name: ($old=$_)
  4. then doing substitution with: s///g operator
  5. finally rename the old file to new one that is $_

NOTE I used print and you should use rename like this:

dir > perl -lne '-f && ($old=$_) && s/file/ABCD/g && rename $old, $_' find.log
dir > find .
.
./00_ABCD.txt
./01_ABCD.txt
./02_ABCD.txt
./dir1
./dir1/00_ABCD.txt
./dir1/01_ABCD.txt
./dir1/02_ABCD.txt
./dir2
./dir2/00_ABCD.txt
./dir2/01_ABCD.txt
./dir2/02_ABCD.txt
./dir3
./dir3/00_ABCD.txt
./dir3/01_ABCD.txt
./dir3/02_ABCD.txt
./find.log 

NOTE Since the find returns list of all files and sub-directories, with this technique Perl renames all the files! Thus first use print then rename. And your pattern can be: -.*(?=\.). In fact:

s/-.*(?=\.)//g
Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44
0

You can do this with a native bash loop:

shopt -s globstar # enable ** for recursive expansion
for file in **/*{j,cs}; do
    # remove everything up to the last . to get extension
    ext=${file##*.}

    # remove everything after the last - and concat with extension
    new_name=${file%-*}$ext 

    # -- prevents weird filenames being interpreted as options
    mv -- "$file" "$new_name" 
done
shopt -u globstar # disable ** if you don't want it anymore e.g. in a script
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141