Change multiple filenames by replacing a character
I have multiple files named like that : screenshot 13:25.png
Windows struggle to open these files probably because of the ":".
How can I replace it?
Solution 1:
In a terminal, cd
into the right directory and then run this.
rename 's/\:/-/g' *.png -vn
This will preview the renaming. It should replace :
with -
.
If that looks right, remove the n
from the end and then it will do the actual renaming.
Note: Ubuntu versions above 17.04 don't ship with rename
, but it's still available in the default repositories, so use sudo apt install rename
to obtain it
Solution 2:
Here's a pure bash solution:
for i in *:*; do
mv -- "$i" "${i//:/_}"
done
The ${var//pattern/replacement}
format will replace all occurrences of pattern
with replacement
in the variable $var
. For more information on bash's string maipulation capabilities, see here.
If you want to do this for multiple characters, you could simply place them in a character class. So, for example, to replace all of ;
,:
,=
,+
,%
,,
with underscores, you could do:
$ ls
1foo:bar 2foo:bar:baz 3foo;bar 4foo=bar 5foo%bar 6foo,bar 7foo+bar
$ for i in *; do mv -- "$i" "${i//[:;=%,+]/_}"; done
$ ls
1foo_bar 2foo_bar_baz 3foo_bar 4foo_bar 5foo_bar 6foo_bar 7foo_bar
Basically, the idea is that [ ]
means any of the characters listed
. So, by placing all of the characters you want to replace in the character class, all of them are dealt with at once.
The --
after mv
signifies the end of options and is needed so that this will work even for file names beginning with -
which otherwise would have been treated as options passed to mv
.
For the specific characters you asked for, things are a bit more complex because some of them need to be escaped (I am ignoring the /
since *nix doesn't allow it in file names any more than Windows does so that won't be an issue):
$ ls
1foo<bar 2foo>bar 3foo:bar 4foo\bar 5foo|bar 6foo*bar 7foo?bar 8foo"bar 9foo'bar
$ for i in *; do mv -- "$i" "${i//[<>:\\|*\'\"?]/_}"; done
$ ls
1foo_bar 2foo_bar 3foo_bar 4foo_bar 5foo_bar 6foo_bar 7foo_bar 8foo_bar 9foo_bar
Note that I escaped the \
,'
and "
by adding a \
in front of each.
Solution 3:
If you prefer a GUI, install pyrenamer:
sudo apt-get install pyrenamer
Then run it:
pyrenamer
It has dozens of options for patterns and renaming formats.
Solution 4:
I prefer GUI but as a Nautilus Extension, i.e. Nautilus Actions Extra:
sudo add-apt-repository ppa:nae-team/ppa
sudo apt-get update
sudo apt-get install nautilus-actions-extra
nautilus -q
(See www.webupd8.org/2011/12/nautilus-actions-extra-pack-of-useful.html)
Then when you select files to be renamed and click Rename from the context menu, you are offered many options for renaming files.