Linux renames files based on input file

I need to rename hundreds of files on Linux in order to change the unique identifier of each command line. For examples, I have a file containing:

old_name1 new_name1 old_name2 new_name2 

and you need to change the names from new to old identifiers. File names contain identifiers, but also have extra characters. So my plan is to:

 abcd_old_name1_1234.txt ==> abcd_new_name1_1234.txt abcd_old_name2_1234.txt ==> abcd_new_name2_1234.txt 

Using rename is obviously pretty useful here, but I'm struggling to decide how to iterate the file with the required name changes and pass this as input to rename ?

Edit: To clarify, I'm looking for hundreds of different renaming commands, the various changes that need to be made are listed in a text file.

Sorry if this is already answered, I have a good hunt, but I can not find a similar case.

+5
source share
3 answers
 while read -r old_name new_name; do rename "s/$old_name/$new_name/" *$old_name*.txt done < file_with_names 

So you read the identifiers from file_with_names and rename the files replacing $old_name with $new_name , leaving the rest of the file name untouched.

+1
source
 rename 's/^(abcd_)old_name(\d+_1234\.txt)$/$1new_name$2/' *.txt 

It should work, depending on whether this package is installed. Also see qmv (rename-utils)

If you need more options, use for example

 shopt -s globstart rename 's/^(abcd_)old_name(\d+_1234\.txt)$/$1new_name$2/' folder/**/*.txt 

(finds all txt files in the subdirectories of the folder ) or

 find folder -type f -iname '*.txt' -exec rename 's/^(abcd_)old_name(\d+_1234\.txt)$/$1new_name$2/' {} \+ 

To do this, use GNU find

+4
source

I was going to write a php function to do this for myself, but I came across a faster method:

ls and copy and paste the contents of the directory into excel from the terminal window. You may need to use a tool to delete or delete online strings . Suppose your file names are in column A in excel, use the following formula in another column:

="mv "&A1&" prefix"&A1&"suffix"

or

="mv "&A1&" "&substitute(A1,"jpeg","jpg")&"suffix"

or

="mv olddirectory/"&A1&" newdirectory/"&A1

back to Linux, create a new file with nano rename.txt and paste the values ​​from excel. They should look something like this:

 mv oldname1.jpg newname1.jpg mv oldname1.jpg newname2.jpg 

then close nano and run the following command: bash rename.txt . Bash simply runs every line in the file, as if you typed it.

and you're done! This method gives a detailed error output, which is convenient.

0
source

Source: https://habr.com/ru/post/1208056/


All Articles