Sunday, May 5, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 3187  / 2 Years ago, thu, november 3, 2022, 10:28:21

I'm having a little problem with renaming a bunch of files in a folder.
The script:



for file in $1 
do
mv $file $file | sed -r 's/^.{20}//' | sed 's/.{16}$//'
done


The output:



mv: cannot move `/home/timothy/Videos/DB/' to a subdirectory of itself, `/home/timothy/Videos/DB/DB'


The SED command is correct, it's just that I'm doing something wrong with the mv parameters.



These are the names of the first 5 files:



[a-s]_dragon_ball_-_001_-_the_secret_of_the_dragon_balls__rs2_[4FC1375C]
[a-s]_dragon_ball_-_002_-_the_emperors_quest__rs2_[59F9C743]
[a-s]_dragon_ball_-_003_-_the_nimbus_cloud_of_roshi__rs2_[0C592F5F]
[a-s]_dragon_ball_-_004_-_oolong_the_terrible__rs2_[47CE4923]
[a-s]_dragon_ball_-_005_-_yamcha_the_desert_bandit__rs2_[B6A035BF]


And it should become this:



001_-_the_secret_of_the_dragon_balls
002_-_the_emperors_quest
003_-_the_nimbus_cloud_of_roshi
004_-_oolong_the_terrible
005_-_yamcha_the_desert_bandit

More From » bash

 Answers
1

I am assuming you have files like,



[a-s]_dragon_ball_-_001_-_the_secret_of_the_dragon_balls__rs2_[4FC1375C]
[a-s]_dragon_ball_-_002_-_the_emperors_quest__rs2_[59F9C743]
[a-s]_dragon_ball_-_003_-_the_nimbus_cloud_of_roshi__rs2_[0C592F5F]
[a-s]_dragon_ball_-_004_-_oolong_the_terrible__rs2_[47CE4923]
[a-s]_dragon_ball_-_005_-_yamcha_the_desert_bandit__rs2_[B6A035BF]


these files have [a-s] at beginning. And you want them after rename as, (according to your comment)



001_-_the_secret_of_the_dragon_balls
002_-_the_emperors_quest
003_-_the_nimbus_cloud_of_roshi
004_-_oolong_the_terrible
005_-_yamcha_the_desert_bandit


Use this script below,



#!/bin/bash
for file in [[a-s]]*
do
newfile=`echo "$file" | sed -r "s/^.{20}//" | awk -F "__rs2" '{print $1}'`
mv $file $newfile
done


How it work



This script scans all filenames in current directory that starts with "[a-s]". Next inside for loop for every scanned file name the script creates new file name leaving first 20 characters filtered throughsed and cuts part starting with string "__rs2" . That removes unwanted parts in the name. And lastly the files are renamed to new file name one by one.



Usage



Save the code as rename_file.sh.(say) Next put it at the same directory where all these files are. Give the script execution permission. Write in terminal,



chmod +x rename_file.sh


Finally to rename the files, just write in terminal,



./rename_file.sh


Done.


[#28171] Friday, November 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lowovey

Total Points: 287
Total Questions: 98
Total Answers: 117

Location: Bosnia and Herzegovina
Member since Thu, Jan 14, 2021
3 Years ago
;