Wednesday, May 1, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 2549  / 3 Years ago, fri, june 4, 2021, 7:45:57

I have many files that i want to move into folders, their names are something like this dir1/dir2/dir3/name_of_file.ex and then maybe another is called /dir4/name_of_file2.xe



Is there anyway of moving those files into the directory dir1/dir2/dir3 and change the name of it to only name_of_file.ex automatically?



I really don't know how i can explain it easier.. but i have almost a 1000 files with names like TSDataResCatalogScriptsdeckfoundations.txt and TSBinSims2.exe and what i want to do with those files is to move into the folder TSDataResCatalogScripts and then rename the file to only deckfoundations.txt. don't know if you know PHP but there you have a explode function where you explode the name of the file with a character



$ar = end(explode("/", $filename));
print_r($ar);


would output something like this



Array
(
[0] => TSDataResCatalogScripts
[1] => deckfoundations.txt
)


Then with that i could use the first row to create the folder if not existing and then rename the full $filename to the second row of $ar


More From » command-line

 Answers
0

I have a script that I use to find, rename, and move files all in one go. You can modify it to suit your purpose if you want; it is currently set to randomly rename files, but you could set a pattern to rename them by.



By the way, the script moves all the files to the current working directory (the one it is executed in), but again that could be modified. You will obviously have to change the ~/Downloads location and substitute the .jpg extensions for what you need.



I am not quite sure that this is exactly what you want, but it may be useful as a template for you and anyone else. Save it in your favourite text editor and make it executable.



NOTE: if you modify the script, but keep the random renaming feature, be aware that occasionally there can be collisions (i.e. the same numbers are generated and the new file is overridden), as there are a limited number of new file names that even two instances of $RANDOM can generate. It is unlikely to happen as the files are being labelled with two sets of random numbers, but it might be better to have a different numbering system if your files are very important or critical in any way.



#!/bin/bash
# a script to recursively find all jpgs in a specified directory, rename with a random label and transfer to pwd

find ~/Downloads -type f -iname '*.jpg' -print0 |
while IFS= read -r -d '' f;
do mv -- "$f" "$RANDOM-$RANDOM.jpg";

done

[#36506] Saturday, June 5, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
inglehare

Total Points: 330
Total Questions: 111
Total Answers: 95

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;