I have a folder with a series of files named:
prefix_1234_567.png
prefix_abcd_efg.png
I'd like to batch remove one underscore and the middle content so the output would be:
prefix_567.png
prefix_efg.png
Relevant but not completely explanatory:
you can install
rename
command by usingbrew
. just dobrew install rename
and use it.In your specific case you can use the following
bash
command (bash
is the default shell on macOS):Note: If there's a chance that your filenames start with
-
, place--
before them[1]:mv -- "$f" "${f/_*_/_}"
Note:
echo
is prepended tomv
so as to perform a dry run. Remove it to perform actual renaming.You can run it from the command line or use it in a script.
"${f/_*_/_}"
is an application ofbash
parameter expansion: the (first) substring matching pattern_*_
is replaced with literal_
, effectively cutting the middle token from the name._*_
is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, runman bash
and search forPattern Matching
).If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based
rename
utility. On macOS you can install it using popular package manager Homebrew as follows:Here's the equivalent of the command at the top using
rename
:Again, this command performs a dry run; remove
-n
to perform actual renaming.bash
solution,s/.../.../
performs text substitution, but - unlike inbash
- true regular expressions are used.[1] The purpose of special argument
--
, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with-
, as Jacob C. notes.To rename files, you can use the
rename
utility:brew install rename
For example, to change a search string in all filenames in current directory:
Remove the 'n' parameter to apply the changes.
More info:
man rename
I had a batch of files that looked like this: be90-01.png and needed to change the dash to underscore. I used this, which worked well:
try this
Here is another way:
Using
mmv