Let's say I have following files: 1.html, 2.html and 3.html and I want to rename them to 1.html-bak, 2.html-bak and 3.html-bak. To do this I run following command:
find . -name '*.html' -print0 | xargs -0 -I {} mv {} {}-bak
Everything is OK, files are renamed as expected.
The question is how to rename them back to *.html
instead of *.html-bak
?
How to remove last 4 chars from string?
You can use ${file%-*}
to get the desired file name back. The following code loops through all files whose name end with html-bak
and performs the renaming by removing everything after the last dash:
for file in *html-bak
do
echo "mv $file ${file%-*}" # <-- using "echo" for safety. Remove once checked
done
${var%-*}
strips the shortest match of *
from back of $var
. That is, removes until the first dash -
is found starting from the right:
$ file="1.h-tml-bak"
$ echo ${file%-*}
1.h-tml
You of course could also use the length, to get everything but the last 4 characters:
$ echo ${file:0:-4}
1.h-tml