[kwlug-disc] bash - file renaming
Chris Irwin
chris at chrisirwin.ca
Thu Sep 26 10:34:28 EDT 2019
On Thu, Sep 26, 2019, at 08:02, Cedric Puddy wrote:
> I've always done as Jason suggests, but the one thing that is usually helpful is the addition of "basename":
>
>> for $FILE in *
>> do
>> mv $FILE $(basename $FILE .htm).whatever
>> done
>
> Basename will remove an arbitrary string (eg: .htm) from the end of another string, thus getting rid of the old extension, so you can tack on your new ".html" or ".whatever" extension.
For a one-off, this is generally what I do too.
However, if you're scripting a loop, it may save a fair amount of time by switching to bash builtins instead of calling basename in every loop. I recently cut down a script that took ~12 seconds to run to about 1 second by eliminating sed and basename calls from within a loop. (the output fed a user screen, so it was noticeable). Also, it stopped churning through a few thousand PIDs while running.
(Also, don't forget quotes, or you'll have a bad time)
for FILE in *
do
# Echo just for safety incase somebody copy/pastes this.
echo mv "$FILE" "${FILE%.*}.whatever"
done
--
*Chris Irwin*
email: chris at chrisirwin.ca
xmpp: chris at chrisirwin.ca
web: https://chrisirwin.ca
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://kwlug.org/pipermail/kwlug-disc_kwlug.org/attachments/20190926/32eec9dc/attachment.htm>
More information about the kwlug-disc
mailing list