Reference: File renaming under Linux, encountering the problem of "bareword not allowed"
Two ways to rename in Linux
There are two commands for renaming files under Linux: mv
, rename
.
mv
Order
mv
The command
mv /dir/file1 /dir2/file1
has two parameters, the first is the source file, and the second is the destination. If the second parameter file name is different, it will be renamed. When the two parameters do not include a directory, only the file name, that's a rename. This is a rename of a single file.
rename
Order
rename
The command
rename arg1 arg2 arg3
rename
is the real batch rename command. And it has 3 parameters, not 2.
arg1
: Old string
arg2
: New string
arg3
: To match the files to be renamed, you can use 3 wildcards, *
, ?
, [char]
.
*
Indicates any number of characters,
?
represents a single character,
[char]
matcheschar
a single customized exact character, and can fill in any characters.
For example,foo[a]*
it means that only file names starting with will be matchedfooa
. If a file isfoobcc.txt
, it will not be matched.
Example
For example, /home
there are two files below abbcc.txt
, addbb.txt
,a.txt
I want to a
replace with xxx
, the command is like this:rename "a" "xxx" *.txt
Then it will first match which files need to be modified. Here, all .txt
files with suffix will be matched.
If it is changed rename "a" "xxx" ?.txt
to , only one file will be matched, that is . Then replace the characters a.txt
in the matched file with . Note that when testing , only the first one will be replaced , which remains to be understood.a
xxx
abab.txt
a
It is worth noting that this command is different in different Linux versions, and the Debian series operating systems have different usage .
rename
Usage of Debian series operating systems
For Debian series operating systems, such as Ubuntu, it is incorrect to use this command in this way, and an error will be reported, such as
Bareword “a” not allowed while “strict subs” in use at (eval 1) line 1.
After searching, I found this statement:
On Debian-based distros it takes a perl expression and a list of files. you need to would need to use:
rename ‘s/foo/foox/’ *
Here is an perl
expression. To be easy to understand, it means that the first two parameters are combined into 1, so only 2 parameters are needed instead of the 3 parameter form mentioned above.
Example
If my current file name is abbcc.txt
, ac.txt
,addbb.txt
So when executing the renaming example above under Ubuntu, the command is as follows:
rename 's/a/xxx/' *.txt
the result is
xxxbbcc.txt
, xxxc.txt
,xxxddbb.txt
Still these three files abbcc.txt
, ac.txt
, addbb.txt
if you want to delete letters a
, then the command is rename 's/a//' *.txt
(that is, just delete the above command xxx
),
and the result is
bbcc.txt
, c.txt
,ddbb.txt
in macOSrename
First, brew install rename
use the installation rename
command, and the rest of the usage is the same as in Ubuntu.