-1

I want to rename my files using a .txt file with proper names These are my files:

lesson1.mp4
lesson2.mp4
lesson3.mp4
...

This is my txt file with names:

1 Entry to vim
2 Basics of vim
3 Vim motion
...

The result I want to have is:

1 Entry to vim.mp4
2 Basics of vim.mp4
3 Vim motion.mp4
don_crissti
  • 82,805
Kirill
  • 9
  • 1
    https://www.google.com/search?q=site%3Aunix.stackexchange.com+rename+files+add+extension may help. There are many questions on unix.stackexchange.com that address renaming by pattern – Chris Davies Dec 13 '22 at 21:52
  • Or https://unix.stackexchange.com/questions/1136/batch-renaming-files – Chris Davies Dec 13 '22 at 21:56
  • Cross-post https://stackoverflow.com/questions/74791172/rename-multiple-files-with-text-file-bash?noredirect=1#comment131994959_74791172 – Arkadiusz Drabczyk Dec 13 '22 at 22:11

1 Answers1

1

Yes, read the lines from the text file into an array, extract the number from each filename and subtract one so that you can use it as array index (bash starts at 0) to select the corresponding element from the array:

readarray -t dest < names_list.txt
for f in lesson*.mp4; do i=${f:6:-4}; mv -- "$f" "${dest[i-1]}.mp4"; done

It's similar with zsh, only that indexing starts at 1 so no need to subtract one from the filename numbers:

zmodload zsh/mapfile
dest=( ${(f@)mapfile[names_list.txt]} )
for f in lesson*.mp4; do i=${f:6:-4}; mv -- "$f" "${dest[i]}.mp4"; done
don_crissti
  • 82,805
  • +1, but ${dest[((i-1))]} could be written as just ${dest[i-1]} in the bash version. From man bash, under the Arrays heading: The subscript is treated as an arithmetic expression that must evaluate to a number. – cas Dec 14 '22 at 06:53
  • @cas - thanks, that's also true for zsh... bad habits always hard to break... – don_crissti Dec 14 '22 at 14:25
  • Thank you so much! – Kirill Dec 14 '22 at 16:20