I have a directory containing thousands of files with names
t_00xx_000xxx.png
I want to change their names to 00xx_000xxx_t.png
so take the prefix and put it as a postfix, can this be done in only one command
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.
Sign up to join this communityI have a directory containing thousands of files with names
t_00xx_000xxx.png
I want to change their names to 00xx_000xxx_t.png
so take the prefix and put it as a postfix, can this be done in only one command
This is possible with the rename
command:
First check what would be done (by suppliying -n
). If it looks good, drop the -n
and run again:
rename -n 's/t_(.+)\.png$/$1_t.png/' *.png # check only
rename 's/t_(.+)\.png$/$1_t.png/' *.png # actually rename the files
/train03_B> rename -n 's/t_(.+)\.png$/$1_t.png/' *.png rename: invalid option -- 'n' Usage: rename [options] <expression> <replacement> <file>... Rename files. Options: -v, --verbose explain what is being done -s, --symlink act on the target of symlinks -h, --help display this help and exit -V, --version output version information and exit For more details see rename(1).
– Mostafa Hussein
Aug 1 '18 at 13:51
If the prefix is separated by an underscore (_
), you can do the following:
rename -n 's/^([^_]*)_(.*)\.(.*)$/$2_$1.$3/' file(s)
It will work with any prefix and any extension.
Remove the -n
to perform the rename if you're happy with the result.
Explanation:
s/search_pattern/replace_pattern/
Search pattern:
^
- Match the beginning of the file name([^_]*)
- Match any character that is not an underscore [^_]*
and capture it as $1
(...)
_
- Match the first underscore(.*)\.(.*)
- Match anything .*
before and after the last .
and capture it as $2
and $3
. The .
must be escaped because it is a special character in Regex --> \.
$
- Match the end of the lineReplace pattern:
$2_$1.$3
- "Filename_Prefix.Extension" from the search pattern captures./train03_B> rename -n 's/t_(.+)\.png$/$1_t.png/' *.png rename: invalid option -- 'n' Usage: rename [options] <expression> <replacement> <file>... Rename files. Options: -v, --verbose explain what is being done -s, --symlink act on the target of symlinks -h, --help display this help and exit -V, --version output version information and exit For more details see rename(1).
– Mostafa Hussein
Aug 1 '18 at 13:53
mmv
(available from the universe
repository) is nice for this kind of thing, where simple shell globs rather than regular expression can do the job
Ex.
mmv -n -- '*_*_*.png' '#2_#3_#1.png'
t_00xx_000xxx.png -> 00xx_000xxx_t.png
Remove the -n
once you are happy that it's working right.