I have several folders containing several video lectures. The names of the files(videos) are like topic blah blah blah - Lecture xx.mp4
I wish to rename them to Lecture xx.mp4
I have written the following bash script. And it appears to hang (gets slow), and doesn't give output also.
for file in *.mp4; do
echo "Renaming file :: $file"
nn=$(grep -o 'Lecture.[0-9]*' "$file")
echo $nn
#mv "$file" "$nn"
done
Kindly help me to correct this script.
Your script searches the content of the file ( grep pattern [FILE...]
), when you actually want to change the $file
parameter value. This should explain, why your command is slow and doesn't seem to work.
To change the value of the $file
parameter, you can use a Bash feature called parameter expansions (see man bash
). In your case ${parameter##word}
, that is remove matching prefix pattern , can be used. ${file##* - }
will strip the longest match of * -
. Note that * -
is not a regular expression but a pattern. Pattern matching is different from regular expressions (compare *
vs. .*
).
#!/usr/bin/bash
for file in *.mp4; do
new=${file##* - }
echo "Renaming '$file' to '$new'"
#mv "$file" "$new"
done
You might find life easier using the rename
program - it is a Perl script. In your case, you would do:
rename --dry-run 's/.*(Lecture \d+)/$1/' *mp4
Output
'topic blah blah blah Lecture 01.mp4' would be renamed to 'Lecture 01.mp4'
'topic blah blah blah Lecture 02.mp4' would be renamed to 'Lecture 02.mp4'
'topic blah blah blah Lecture 555556.mp4' would be renamed to 'Lecture 555556.mp4'
Then remove the --dry-run
if you like what it says. It has the advantage over most ad-hoc shell scripts that it will not clobber files and you can do dry runs, and it supports the full Perl syntax so you can do very complicated things easily.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.