Home > Net >  Bash - How to rename files inside a directory based on names.txt
Bash - How to rename files inside a directory based on names.txt

Time:05-01

I'm sorry I can't provide the actual filenames for privacy reasons.

names.txt contains several groups of lines separated by a single empty line. Each group pertains to a particular file. The number of lines in each group of lines varies. The only similarity between these groups of lines is that every 1st lines refers to the oldname of a certain file while every 2nd line refers to the desired newname for the said file.

These lines have no spaces in them. There are some other characters like numbers, underscore, ampersand and forward slash though.

names.txt is inside the same directory and it looked like this:

a1.pdf
Newname_for_a1.pdf
--some-texts--

b2.pdf
Newname_for_b2.pdf
--some-texts--
--some-texts--

c3.pdf
Newname_for_c3.pdf
--some-texts--
--some-texts--

d4.pdf
Newname_for_d4.pdf
--some-texts--
--some-texts--
--some-texts--

--more_texts_below--

The oldname starts with a lowercase while the newname starts with uppercase both with a .pdf extension

ls will give

a1.pdf
b2.pdf
c3.pdf
d4.pdf
names.txt
several-filenames-below

Can I do this in Bash? Please help.

edit. Initially I want to work on having 2 .txt files, oldnames.txt and newnames.txt and then I realized maybe there is another way of doing this with just 1 txt file.

What I've tried already is watched some video tutorials about regular expressions in relation to grep but I feel like i will understand it better if I will do actual text manipulations such as finding, moving, renaming files since I am also in the process of sorting and organizing some hundred Gbs of media files and personal documents.

I'm looking into this thread now

How to rename files with filename from one txt file to filename from another txt file in bash?

edit2 I can now grep the instances of 1st lines (oldnames) in each group from names.txt by grep --color -n -E "^[a-z].*\.pdf$" names.txt and the instances of 2nd lines (newnames) in each group from names.txt by grep --color -n -E "^[A-Z].*\.pdf$" names.txt

CodePudding user response:

Since rename operation with mv command is not reversible.

  1. Suggesting to write all mv commands into a file renames.sh.

    awk '{print "mv \""$1"\"", "\""$2"\""}' RS="\n\n" RSnames.txt > renames.sh
    
  2. Inspect and correct the renames.sh file.

Note: clear all quotes ' and/or double-quotes " from your file names. Each file name needs to be wrapped in double-quotes ". Script will fail if there is ' or " in file name.

  1. Execute all mv commands in a renames.sh file. By running the renames.sh files as a script.

    bash renames.sh
    

awk script explantion:

RS="\n\n"

Set awk record separator to empty line.

print "mv \""$1"\"", "\""$2"\""

Print a bash command mv "file1" "file2" .

File1 retrieved from 1st awk field $1, File2 retrieved from 2nd awk field $2.

  • Related