2

i want to rename multiple files in my linux system directory....

my file names are as:

Lec 1 - xxx.webm
Lec 2 - xxx.webm
Lec 3 - xxx.webm
Lec 4 - xxx.webm

and the list goes on...

here xxx could be any list of characters(not consistent)....

i would like to rename every file in here like:

mv Lec 1 - xxx.webm Lec 1.webm
mv Lec 2 - xxx.webm Lec 2.webm
mv Lec 3 - xxx.webm Lec 3.webm

and so on....

for in loop could do but how to do the substitution?

*strip all characters after the number should be my renamed file

coolstoner
  • 719
  • 2
  • 9
  • 20

3 Answers3

2

This for loop should do the job:

for f in *.webm; do
   mv "$f" "${f/ -*/}.webm"
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • the file name changed to `Lec n - webm.webm` – coolstoner Jul 30 '16 at 10:59
  • No `${f/ -*/}` will strip everything after `" -"` in original string and then `.webm` will be added back. – anubhava Jul 30 '16 at 11:24
  • now all my files have been renamed to `Lec n.webm.webm` can you help me rename it back to `Lec n.webm` only? i tried this link but i get error http://unix.stackexchange.com/questions/102647/how-to-rename-multiple-files-in-single-command-or-script-in-unix – coolstoner Jul 30 '16 at 11:34
  • Yes you can use this loop: `for f in *.webm.webm; do echo mv "$f" "${f%.webm}"; done` to fix those filenames – anubhava Jul 30 '16 at 11:42
  • i try this and i get error `for file in $(find . -name "*webm") do mv "$file" "${file/.webm/ }" done` ` mv: cannot stat '7.webm.webm': No such file or directory mv: cannot stat './Lec': No such file or directory mv: cannot stat '8.webm.webm': No such file or directory mv: cannot stat './Lec': No such file or directory mv: cannot stat '9.webm.webm': No such file or directory ` – coolstoner Jul 30 '16 at 12:10
  • 1
    But I didn't give you any `find` command to start with. Besides `"${file/.webm/ }"` is just wrong. If you want to use find then use: **`find . -name '*.webm.webm' -exec bash -c 'mv "$1" "${1%.webm}"' - {} \;`** – anubhava Jul 30 '16 at 12:30
  • thanks its resolved! may i know why this is wrong? `"${file/.webm/ }"` – coolstoner Jul 30 '16 at 12:34
  • `"${file/.webm/ }"` will convert `'a.webm.webm'` into `'a .webm'` – anubhava Jul 30 '16 at 12:43
2

${string%substring}: deletes shortest match of $substring from back of $string.

for i in *.webm; do mv $i ${i%xxx}; done

Or check out:

${string%%substring}: deletes longest match of $substring from back of $string.

SLePort
  • 15,211
  • 3
  • 34
  • 44
Meiko Watu
  • 451
  • 1
  • 4
  • 11
1

If you have util-linux-ng installed:

find . -name "Lec*.webm" | xargs rename s/ -*//

or:

for file in $(find . -name "Lec*.webm")
do 
  echo mv "$file" "`echo $file | sed s/ -*$//`"
done
guido
  • 18,864
  • 6
  • 70
  • 95