From my mailbag:
“How do I rename multiple files at a shell prompt under a Linux or UNIX operating systems?”
Renaming multiple files at a shell prompt is always considered as a black art by many Linux and UNIX gurus. To be frank if you understand regex then it is not a black art anymore. A regular expression is a string that describes or matches a set of strings, according to certain syntax rules. Linux and *BSD/Unix comes with handy utility called rename. As a name suggest ‘rename’ command renames the filenames supplied according to the rule specified (syntax):
rename "regex-rule" files
Linux Rename Multiple Files Command
The rename command discussed here is nothing but a Perl script. You can download the script as described below. Let us see how to rename multiple files in single command or shell script in Unix or Linux operating system using various methods and commands. Please note that you can install this tool on MacOS using the following brew command:
$ brew install rename
Rename command syntax
It is a faster way to group rename files in Linux or Unix-like system. The syntax is:
rename oldname newname *.files
On most modern Linux distros rename command is known as rename.ul:
rename.ul oldname newname *.files
For example rename all *.bak file as *.txt, enter:
$ rename .bak .txt *.bak
Please note that the rename command is part of the util-linux package and can be installed on a Debian or Ubuntu Linux, using the following apt command/apt-get command:
$ sudo apt-get install renameutils
How to rename multiple files with the zmv under zsh
First load zmv and then use it:
$ autoload -U zmv
To rename all files to lower case, enter:
$ zmv '*' '${(L)f}'
See zshwiki for more info on zmv.
Renaming multiple files with the mmv command
You can use the mmv command to move/copy/append/link multiple files.
Install mmv on a Debian or Ubuntu Linux
Type the following apt-get command to install mmv utility, enter:
$ sudo apt-get install mmv
Sample outputs:
Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: mmv 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 28.2 kB of archives. After this operation, 89.1 kB of additional disk space will be used. Get:1 http://mirrors.service.networklayer.com/ubuntu/ trusty/universe mmv amd64 1.01b-18 [28.2 kB] Fetched 28.2 kB in 0s (1,828 kB/s) Selecting previously unselected package mmv. (Reading database ... 64911 files and directories currently installed.) Preparing to unpack .../mmv_1.01b-18_amd64.deb ... Unpacking mmv (1.01b-18) ... Processing triggers for man-db (2.6.7.1-1ubuntu1) ... Setting up mmv (1.01b-18) ...
Install mmv utility on a CentOS/RHEL/Fedora Linux
Type the following yum command to install mmv, enter:
# yum install mmv
Fedora Linux user, type:
$ sudo dnf install mmv
How do I use mmv command?
Let us convert all filenames to lowercase in bulk, enter:
$ mmv "*" "#l1"
Next I am going rename all ‘*.bakz’ files in the current directory to ‘*.bak’, run:
$ mmv '*.bakz' '#1.bak'
See the mmv command man page for further informmation:
man mmv
Examples: Linux Rename Multiple Files Using a Shell Script
Convert all mp3 filenames to more readable and usable format. Most of the time MP3 got multiple blank spaces, which may confuse many command line based Linux utilities and mp3 players
$ ls
Sample outputs:
06 - Gorillaz - Feel Good Inc.mp3 DDR - Kung- Fu Fighting (bus stop).mp3 AXEL CRAZYFROG.mp3
Remove all blank space with rename command:
$ rename "s/ *//g" *.mp3
$ ls
Sample outputs:
06-Gorillaz-FeelGoodInc.mp3 DDR-Kung-FuFighting(busstop).mp3 AXEL-CRAZYFROG.mp3
POSIX shell rename all *.bak to *.txt
Use bash shell for loop as follows:
for j in *.bak; do mv -- "$j" "${j%.bak}.txt"; done
OR
for j in *.bak; do mv -v -- "$j" "${j%.bak}.txt"; done
Linux Shell script to rename files
Before using the rename command I was using the following shell script to rename my mp3s :
WARNING: This is a demo script and it is not very safe to use. I suggest either use rename/zmv or POSIX shell method
#!/bin/bash # To remove blank space if [ $# -eq 0 ]; then echo "Syntax: $(basename $0) file-name [command]" exit 1 fi FILES=$1 CMD=$2 for i in $FILES do # remove all blanks and store them OUT OUT=$(echo $i | sed 's/ *//g') if [ "$CMD" == "" ]; then #just show file echo $OUT else #else execute command such as mv or cp or rm [ "$i" != "$OUT" ] && $($CMD "$i" "$OUT") fi done
See mv command for more info.
Perl Script To Rename File
Download the following script and save as rename in /usr/local/bin/ directory or $HOME/bin and run it as follows:
$ ~/bin/rename 'y/A-Z/a-z/' *
OR
$ /usr/local/bin/rename 'y/A-Z/a-z/' *
Delete or remove .jpg file extension, you write command as follows:
$ rename 's/\.jpg$//' *.jpg
Want to convert all uppercase filenames to lowercase? Try
$ rename 'y/A-Z/a-z/' *
To rename all files matching “*.txtz” to strip the extension, enter:
$ rename 's/\.txtz$//' *.txtz
Read the man page of rename command for more information:
$ man rename
Perl script (download):
#!/usr/bin/env perl use strict; use warnings; use Getopt::Long 2.24, qw( :config bundling no_ignore_case no_auto_abbrev ); my ( $N, $EXT, @EXT, @USE, $DECODE, $ENCODE ); sub compile { eval shift } # defined early to control the lexical environment my $msglevel = 0; sub ERROR (&) { print STDERR $_[0]->(), "\n" if $msglevel > -1 }; sub INFO (&) { print STDERR $_[0]->(), "\n" if $msglevel > 0 }; sub DEBUG (&) { print STDERR $_[0]->(), "\n" if $msglevel > 1 }; sub pod2usage { require Pod::Usage; goto &Pod::Usage::pod2usage } sub mkpath { require File::Path; goto &File::Path::mkpath } sub dirname { require File::Basename; goto &File::Basename::dirname } use constant VERB_FOR => { link => { inf => 'link', pastp => 'linked', exec => sub { link shift, shift }, }, symlink => { inf => 'symlink', pastp => 'symlinked', exec => sub { symlink shift, shift }, }, rename => { inf => 'rename', pastp => 'renamed', exec => sub { rename shift, shift }, }, }; sub argv_to_subst_expr { my $modifier = shift || ''; pod2usage( -verbose => 1 ) if @ARGV < 2; my ($from, $to) = map quotemeta, splice @ARGV, 0, 2; # the ugly \${\""} construct is necessary because unknown backslash escapes are # not treated the same in pattern- vs doublequote-quoting context; only the # latter lets us do the right thing with problematic input like # ']{ool(haracter$' or maybe '>><//((/>' sprintf 's/\Q${\"%s"}/%s/%s', $from, $to, $modifier; } sub pipe_through { my ( $cmd ) = @_; IPC::Open2::open2( my $in, my $out, $cmd ) or do { warn "couldn't open pipe to $cmd: $!\n"; return; }; print $out $_; close $out; $_ = <$in>; chomp; close $in; } my ( $VERB, @EXPR ); my %library = ( camelcase => 's/([[:alpha:]]+)/\u$1/g', urlesc => 's/%([0-9A-F][0-9A-F])/chr hex $1/ieg', nows => 's/[_[:blank:]]+/_/g', rews => 'y/_/ /', noctrl => 's/[_[:cntrl:]]+/_/g', nometa => 'tr/_!"&()=?`*\':;<>|$/_/s', trim => 's/\A[ _]+//, s/[ _]+\z//' ); GetOptions( 'h|help' => sub { pod2usage() }, 'man' => sub { pod2usage( -verbose => 2 ) }, '0|null' => \my $opt_null, 'f|force' => \my $opt_force, 'g|glob' => \my $opt_glob, 'i|interactive' => \my $opt_interactive, 'k|backwards|reverse-order' => \my $opt_backwards, 'l|symlink' => sub { $VERB ? pod2usage( -verbose => 1 ) : ( $VERB = VERB_FOR->{ 'symlink' } ) }, 'L|hardlink' => sub { $VERB ? pod2usage( -verbose => 1 ) : ( $VERB = VERB_FOR->{ 'link' } ) }, 'M|use=s' => \@USE, 'n|just-print|dry-run' => \my $opt_dryrun, 'N|counter-format=s' => \my $opt_ntmpl, 'p|mkpath|make-dirs' => \my $opt_mkpath, 'stdin!' => \my $opt_stdin, 't|sort-time' => \my $opt_time_sort, 'T|transcode=s' => \my $opt_transcode, 'v|verbose+' => \$msglevel, 'a|append=s' => sub { push @EXPR, "\$_ .= qq[${\quotemeta $_[1]}]" }, 'A|prepend=s' => sub { push @EXPR, "substr \$_, 0, 0, qq[${\quotemeta $_[1]}]" }, 'c|lower-case' => sub { push @EXPR, 's/([[:upper:]]+)/\L$1/g' }, 'C|upper-case' => sub { push @EXPR, 's/([[:lower:]]+)/\U$1/g' }, 'd|delete=s' => sub { push @EXPR, "s/${\quotemeta $_[1]}//" }, 'D|delete-all=s' => sub { push @EXPR, "s/${\quotemeta $_[1]}//g" }, 'e|expr=s' => \@EXPR, 'P|pipe=s' => sub { require IPC::Open2; push @EXPR, "pipe_through '\Q$_[1]\E'" }, 's|subst' => sub { push @EXPR, argv_to_subst_expr }, 'S|subst-all' => sub { push @EXPR, argv_to_subst_expr('g') }, 'x|remove-extension' => sub { push @EXPR, 's/\. [^.]+ \z//x' }, 'X|keep-extension' => sub { push @EXPR, 's/\.([^.]+)\z//x and do { push @EXT, $1; $EXT = join ".", reverse @EXT }' }, 'z|sanitize' => sub { push @EXPR, @library{ qw( nows noctrl nometa trim ) } }, map { my $recipe = $_; $recipe => sub { push @EXPR, $library{ $recipe } } } keys %library, ) or pod2usage(); $opt_stdin = @ARGV ? 0 : 1 unless defined $opt_stdin; $VERB ||= VERB_FOR->{ 'rename' }; if ( not @EXPR ) { pod2usage() if not @ARGV or -e $ARGV[0]; push @EXPR, shift; } pod2usage( -message => 'Error: --stdin and filename arguments are mutually exclusive' ) if $opt_stdin and @ARGV; pod2usage( -message => 'Error: --null only permitted when reading filenames from STDIN' ) if $opt_null and not $opt_stdin; pod2usage( -message => 'Error: --interactive and --force are mutually exclusive' ) if $opt_interactive and $opt_force; my $n = 1; my $nwidth = 0; if ( defined $opt_ntmpl ) { $opt_ntmpl =~ /\A(?:(\.\.\.0)|(0+))([0-9]+)\z/ or pod2usage( -message => "Error: unparseable counter format $opt_ntmpl" ); $nwidth = ( defined $1 ? -1 : defined $2 ? length $opt_ntmpl : 0 ); $n = $3; } ++$msglevel if $opt_dryrun; my $code = do { if ( $opt_transcode ) { require Encode; my ( $in_enc, $out_enc ) = split /:/, $opt_transcode, 2; $DECODE = Encode::find_encoding( $in_enc ); die "No such encoding $in_enc\n" if not ref $DECODE; $ENCODE = defined $out_enc ? Encode::find_encoding( $out_enc ) : $ENCODE; die "No such encoding $out_enc\n" if not ref $ENCODE; unshift @EXPR, '$_ = $DECODE->decode($_)'; push @EXPR, '$_ = $ENCODE->encode($_)'; } my $i = $#USE; for ( reverse @USE ) { s/\A([^=]+)=?//; my $use = "use $1"; $use .= ' split /,/, $USE['.$i--.']' if length; unshift @EXPR, $use; } if ( eval 'require feature' and $^V =~ /^v(5\.[1-9][0-9]+)/ ) { unshift @EXPR, "use feature ':$1'"; } my $cat = sprintf 'sub { %s }', join '; ', @EXPR; DEBUG { "Using expression: $cat" }; my $evaled = compile $cat; die $@ if $@; die "Evaluation to subref failed. Check expression using -nv\n" unless 'CODE' eq ref $evaled; $evaled; }; if ( $opt_stdin ) { local $/ = $/; INFO { "Reading filenames from STDIN" }; @ARGV = do { if ( $opt_null ) { INFO { "Splitting on NUL bytes" }; $/ = chr 0; } ; }; chomp @ARGV; } @ARGV = map glob, @ARGV if $opt_glob; if ( $opt_time_sort ) { my @mtime = map { (stat)[9] } @ARGV; @ARGV = @ARGV[ sort { $mtime[$a] <=> $mtime[$b] } 0 .. $#ARGV ]; } @ARGV = reverse @ARGV if $opt_backwards; $nwidth = length $n+@ARGV if $nwidth < 0; for ( @ARGV ) { my $old = $_; $N = sprintf '%0*d', $nwidth, $n++; $code->(); $_ = join '.', $_, reverse splice @EXT if @EXT; if ( $old eq $_ ) { DEBUG { "'$old' unchanged" }; next; } if ( !$opt_force and -e ) { ERROR { "'$old' not $VERB->{pastp}: '$_' already exists" }; next; } if ( $opt_dryrun ) { INFO { "'$old' would be $VERB->{pastp} to '$_'" }; next; } if ( $opt_interactive ) { print "\u$VERB->{inf} '$old' to '$_'? [n] "; if ( !~ /^y(?:es)?$/i ) { DEBUG { "Skipping '$old'." }; next; } } my ( $success, @made_dirs ); ++$success if $VERB->{ 'exec' }->( $old, $_ ); if ( !$success and $opt_mkpath ) { @made_dirs = mkpath( [ dirname( $_ ) ], $msglevel > 1, 0755 ); ++$success if $VERB->{ 'exec' }->( $old, $_ ); } if ( !$success ) { ERROR { "Can't $VERB->{inf} '$old' to '$_': $!" }; rmdir $_ for reverse @made_dirs; next; } INFO { "'$old' $VERB->{pastp} to '$_'" }; } __END__ =head1 NAME rename - renames multiple files =head1 VERSION version 1.600 =head1 SYNOPSIS F B<[switches|transforms]> B<[files]> Switches: =over 1 =item B<-0>/B<--null> (when reading from STDIN) =item B<-f>/B<--force>EorEB<-i>/B<--interactive> (proceed or prompt when overwriting) =item B<-g>/B<--glob> (expand C<*> etc. in filenames, useful in WindowsE F) =item B<-k>/B<--backwards>/B<--reverse-order> =item B<-l>/B<--symlink>EorEB<-L>/B<--hardlink> =item B<-M>/B<--use=I> =item B<-n>/B<--just-print>/B<--dry-run> =item B<-N>/B<--counter-format> =item B<-p>/B<--mkpath>/B<--make-dirs> =item B<--stdin>/B<--no-stdin> =item B<-t>/B<--sort-time> =item B<-T>/B<--transcode=I> =item B<-v>/B<--verbose> =back Transforms, applied sequentially: =over 1 =item B<-a>/B<--append=I> =item B<-A>/B<--prepend=I> =item B<-c>/B<--lower-case> =item B<-C>/B<--upper-case> =item B<-d>/B<--delete=I> =item B<-D>/B<--delete-all=I> =item B<-e>/B<--expr=I<code>> =item B<-P>/B<--pipe=I> =item B<-s>/B<--subst I I> =item B<-S>/B<--subst-all I I> =item B<-x>/B<--remove-extension> =item B<-X>/B<--keep-extension> =item B<-z>/B<--sanitize> =item B<--camelcase>EB<--urlesc>EB<--nows>EB<--rews>EB<--noctrl>EB<--nometa>EB<--trim> (see manual) =back =head1 DESCRIPTION This program renames files according to modification rules specified on the command line. If no filenames are given on the command line, a list of filenames will be expected on standard input. The documentation contains a L. =head1 OPTIONS =head2 Switches =over 4 =item B<-h>, B<--help> See a synopsis. =item B<--man> Browse the manpage. =item B<-0>, B<--null> When reading file names from C, split on NUL bytes instead of newlines. This is useful in combination with GNU find's C<-print0> option, GNU grep's C<-Z> option, and GNU sort's C<-z> option, to name just a few. B =item B<-f>, B<--force> Rename even when a file with the destination name already exists. =item B<-g>, B<--glob> Glob filename arguments. This is useful if you're using a braindead shell such as F which won't expand wildcards on behalf of the user. =item B<-i>, B<--interactive> Ask the user to confirm every action before it is taken. =item B<-k>, B<--backwards>, B<--reverse-order> Process the list of files in reverse order, last file first. This prevents conflicts when renaming files to names which are currently taken but would be freed later during the process of renaming. =item B<-l>, B<--symlink> Create symlinks from the new names to the existing ones, instead of renaming the files. B.> =item B<-L>, B<--hardlink> Create hard links from the new names to the existing ones, instead of renaming the files. B.> =item B<-M>, B<--use> Like perl's own C<-M> switch. Loads the named modules at the beginning of the rename, and can pass import options separated by commata after an equals sign, i.e. C<Module=foo,bar> will pass the C and C import options to C. You may load multiple modules by using this option multiple times. =item B<-n>, B<--dry-run>, B<--just-print> Show how the files would be renamed, but don't actually do anything. =item B<-N>/B<--counter-format> Format and set the C<$N> counter variable according to the given template. E.g. C<-N 001> will make C<$N> start at 1 and be zero-padded to 3 digits, whereas C<-N 0099> will start the counter at 99 and zero-pad it to 4 digits. And so forth. Only digits are allowed in this simple form. As a special form, you can prefix the template with C<...0> to indicate that C should determine the width automatically based upon the number of files. E.g. if you pass C<-N ...01> along with 300 files, C<$N> will range from C<001> to C<300>. =item B<-p>, B<--mkpath>, B<--make-dirs> Create any non-existent directories in the target path. This is very handy if you want to scatter a pile of files into subdirectories based on some part of their name (eg. the first two letters or the extension): you don't need to make all necessary directories beforehand, just tell C to create them as necessary. =item B<--stdin>, B<--no-stdin> Always E or never E read the list of filenames from STDIN; do not guess based on the presence or absence of filename arguments. B.> =item B<-T>, B<--transcode> Decode each filename before processing and encode it after processing, according to the given encoding supplied. To encode output in a different encoding than input was decoded, supply two encoding names, separated by a colon, e.g. C<-T latin1:utf-8>. Only the last C<-T> parameter on the command line is effective. =item B<-v>, B<--verbose> Print additional information about the operations (not) executed. =back =head2 Transforms Transforms are applied to filenames sequentially. You can use them multiple times; their effects will accrue. =over 4 =item B<-a>, B<--append> Append the string argument you supply to every filename. =item B<-A>, B<--prepend> Prepend the string argument you supply to every filename. =item B<-c>, B<--lower-case> Convert file names to all lower case. =item B<-C>, B<--upper-case> Convert file names to all upper case. =item B<-e>, B<--expr> The C<code> argument to this option should be a Perl expression that assumes the filename in the C<$_> variable and modifies it for the filenames to be renamed. When no other C<-c>, C<-C>, C<-e>, C<-s>, or C<-z> options are given, you can omit the C<-e> from infront of the code. =item B<-P>, B<--pipe> Pass the filename to an external command on its standard input and read back the transformed filename on its standard output. =item B<-s>, B<--subst> Perform a simple textual substitution of C to C. The C and C parameters must immediately follow the argument. =item B<-S>, B<--subst-all> Same as C<-s>, but replaces I instance of the C text by the C text. =item B<-x>, B<--remove-extension> Remove the last extension from a filename, if there is any. =item B<-X>, B<--keep-extension> Save and remove the last extension from a filename, if there is any. The saved extension will be appended back to the filename at the end of the rest of the operations. Repeating this option will save multiple levels of extension in the right order. =item B<-z>, B<--sanitize> A shortcut for passing C<--nows --noctrl --nometa --trim>. =item B<--camelcase> Capitalise every separate word within the filename. =item B<--urlesc> Decode URL-escaped filenames, such as wget(1) used to produce. =item B<--nows> Replace all sequences of whitespace in the filename with single underscore characters. =item B<--rews> Reverse C<--nows>: replace each underscore in the filename with a space. =item B<--noctrl> Replace all sequences of control characters in the filename with single underscore characters. =item B<--nometa> Replace every shell meta-character with an underscore. =item B<--trim> Remove any sequence of spaces and underscores at the left and right ends of the filename. =back =head1 VARIABLES These predefined variables are available for use within any C<-e> expressions you pass. =over 4 =item B<$N> A counter that increments for each file in the list. By default, counts up from 1. The C<-N> switch takes a template that specifies the padding and starting value of C<$N>; see L. =item B<$EXT> A string containing the accumulated extensions saved by C<-X> switches, without a leading dot. See L. =item B<@EXT> An array containing the accumulated extensions saved by C<-X> switches, from right to left, without any dots. The right-most extension is always C<$EXT[0]>, the left-most (if any) is C<$EXT[-1]>. =back =head1 TUTORIAL F takes a list of filenames, runs a list of modification rules against each filename, checks if the result is different from the original filename, and if so, renames the file. The most I way to use it is to pass a line of Perl code as the rule; the most I way is to employ the many switches available to supply rules for common tasks such as stripping extensions. For example, to strip the extension from all C<.bak> files, you might use either of these command lines: rename -x *.bak rename 's/\.bak\z//' * These do not achive their results in exactly the same way: the former only takes the files that match C<*.bak> in the first place, then strips their last extension; the latter takes all files and strips a C<.bak> from the end of those filenames that have it. As another alternative, if you are confident that none of the filenames has C<.bak> anywhere else than at the end, you might instead choose to write the latter approach using the C<-s> switch: rename -s .bak '' * Of course you can do multiple changes in one go: rename -s .tgz .tar.gz -s .tbz2 .tar.bz2 *.t?z* But note that transforms are order sensitive. The following will not do what you probably meant: rename -s foo bar -s bar baz * Because rules are cumulative, this would first substitute F with F; in the resulting filenames, it would then substitute F with F. So in most cases, it would end up substituting F with F E probably not your intention. So you need to consider the order of rules. If you are unsure that your modification rules will do the right thing, try doing a verbose dry run to check what its results would be. A dry run is requested by passing C<-n>: rename -n -s bar baz -s foo bar * You can combine the various transforms to suit your needs. E.g. files from MicrosoftE WindowsE systems often have blanks and (sometimes nothing but) capital letters in their names. Let's say you have a heap of such files to clean up, I you also want to move them to subdirectories based on extension. The following command will do this for you: rename -p -c -z -X -e '$_ = "$EXT/$_" if @EXT' * Here, C<-p> tells F to create directories if necessary; C<-c> tells it to lower-case the filename; C<-X> remembers the file extension in the C<$EXT> and C<@EXT> variables; and finally, the C<-e> expression uses those to prepend the extension to the filename as a directory, I there is one. That brings us to the secret weapon in F's arsenal: the C<-X> switch. This is a transform that clips the extension off the filename and stows it away at that point during the application of the rules. After all rules are finished, the remembered extension is appended back onto the filename. (You can use multiple C<-X> switches, and they will accumulate multiple extensions as you would expect.) This allows you to do use simple way for doing many things that would get much trickier if you had to make sure to not affect the extension. E.g.: rename -X -c --rews --camelcase --nows * This will uppercase the first letter of every word in every filename while leaving its extension exactly as before. Or, consider this: rename -N ...01 -X -e '$_ = "File-$N"' * This will throw away all the existing filenames and simply number the files from 1 through however many files there are E except that it will preserve their extensions. Incidentally, note the C<-N> switch and the C<$N> variable used in the Perl expression. See L and L for documentation. =head1 COOKBOOK Using the C<-M> switch, you can quickly put F to use for just about everything the CPAN offers: =head3 Coarsely latinize a directory full of files with non-Latin characters rename -T utf8 -MText::Unidecode '$_ = unidecode $_' * See L. =head3 Sort a directory of pictures into monthwise subdirectories rename -p -MImage::EXIF '$_ = "$1-$2/$_" if Image::EXIF->new->file_name($_) ->get_image_info->{"Image Created"} =~ /(\d\d\d\d):(\d\d)/' *.jpeg See L. =head1 SEE ALSO mv(1), perl(1), find(1), grep(1), sort(1) =head1 BUGS None currently known. =head1 AUTHORS Aristotle Pagaltzis Idea, inspiration and original code from Larry Wall and Robin Barker. =head1 COPYRIGHT This script is free software; you can redistribute it and/or modify it under the same terms as Perl itself. </code></code>
🐧 Get the latest tutorials on Linux, Open Source & DevOps via:
- RSS feed or Weekly email newsletter
- Share on Twitter • Facebook • 132 comments... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Kindly help me on the below details.
i have a file ,named as a_file.20167654 and now i want to rename it as a_file_20167654.txt
kindly help me on this.
For single file just use the mv command:
mv -v a_file.20167654 a_file_20167654.txt
Hi,
Urgent…!!
Please help me in renaming below file using bash script.
I have multiple files in one directory with same format, so i want to rename all like below
From
31-07-2017filename.log
To
filename_31-07-2017_1.log
Please don’t suggest using “rename” cmd . “rename” cmd not working in my linux server.
Thank you
Hi,
Urgent…!!
Please help me in renaming below file using bash script.
From
31-07-2017filename.log
To
filename_31-07-2017_1.log
Please don’t suggest using “rename” cmd . “rename” cmd not working in my linux server.
Thank you
Hi! If I want to rename all files in a linux folder to include their CREATED AT time in their name, what can I do?
example:
I have a file hello.mp4 that was created on july 15 10:30
it should be:
hello_07_30_2016_10:30.mp4
Or any format.
Thank you very much!
How to add a prefix to original file names.
POLL91.DWN —-> GSTD.20160401160515.POLL91
POLL57.DWN —-> SMAL.20160401153035.POLL57
POLL61.DWN —-> ETNC.20160401171109.POLL61
Thanks for help
Hi, I have multiple file in a directory, those are (for example):
kefjlakjdw.dh
dlaleojgkkj.dh
ldjwoqejklr.dh
I would like to rename them to:
1.sh
2.sh
3.sh
in which 1,2,3 is the order of files presented when we use ‘ls’ command.
Could anyone help me in this case?
Thanks so much!
Phuong.
Hi, sorry, I just moved to Linux.
what would be the easyest equivalent of
rename *.pptx *.ppt
Thanks
how about
mv *.{bak,txt}
I gave up using the above for changing some files in Linux (change the first letter in every file so pretty straight forward) and simply sent them to a Windows box and did a “ren s*.jpg l*.jpg” and then sent them back. Sometimes I wish we not only had the power in Linux but perhaps some of the ease of use and userfriendliness that was added back in DOS around the mid 80’s.
Ankit: mv changing_colorlow_actual_take000000 changing_colorlow_expected
?
Hi,
I want to change:
Input: changing_colorlow_actual_take000000
Output: changing_colorlow_expected
What is the Code for it??
Have to be careful with the replacement – in your first example it will grab any portion of the file name that matches. So if you have a file named “add.bak1.bak” it will be changed to “add.txt1.bak”. I know this is being picky but in automaton of bulk changes, you must be very strict or you will be stuck with unintended results.
Hi,
I’m working on renaming the folders using linux , where I need to rename some 100 folders in one single time as follows:
For example:
Say, the following are the subject ids (folder names):
11001
11002
11003
11004
11005……
Here, there are 5 folders. And I have an excel spreadsheet which holds these
SUBJECT IDs in one column and their corresponding subject name in another column.
Say subject names are
english
maths
physics
chemistry
computer….
I need to rename my subject id as follows:(using linux scripting)
11001 – english
11002 – maths
11003 – physics
11004 – chemistry
11005 – computer
Can anyone plz help me to sort this out???
for i in F4200*; do mv $i OLD_$i; done
Hello
My request here is much more simple but cannot get this to work
(Linux RedHat 2.6.32-358.14.1.el6.x86_64)
I’d like to rename (i have hunder of F4200* files)
F4200BNP2
F4200BNP3
F4200BNP4
F4200BNP5
F4200BNP6
Into
OLD_F4200BNP2
OLD_F4200BNP3
OLD_F4200BNP4
OLD_F4200BNP5
OLD_F4200BNP6
Thanks for your help
hw could i rename files in a directory such as s ser sde to 1s 2ser 3sde like tat could u please help me out ?
Hi I need help, i am using cygwin & trying to copy & create multiple files in a sequence eg :-
filename_1234609 I need to duplicate this file muliple times creating an incremental sequence number
eg
filename_1234609
filename_1234610
filename_1234611
al the way to filename_1234700
can anyone help ?/
I am trying to cp a file & rename with a sequence
ls * | while read line; do mv $line $line.txt; done
will rename all files in that folder to .txt extension
for i in `ls`; do `mv $i $i.orig`; done
To change all file with ‘php’ format to ‘jpg’ in a folder:
rename ‘s/.php$/.jpg/’ *.php
My problem was that when copying files from linux to Windows, Windows would complain about the filenames that were longer than what Windows can handle.
I tried a few of the examples posted here previously but they didn’t work for me either (I’m running Fedora 17 64-bit) so I wrote my own … Copy the following text to a plain file and save it as a shell script – don’t forget to make it executable (chmod a+x “whateverYouSavedItAs.sh”)
#start script
for filename in *.jpg
do
fname=`echo $filename | cut -c1-137`;
nname=’newFileNameSequence’;
run(){
rename $fname $nname *.jpg
}
run
done
So what I’m doing is looking at everything up to the 137th position in the filename that I want to work with as the repeating pattern, then assigning my new file name pattern in the variable “nname”. The result is a shorter file name (also in numeric sequence) that Windows can handle. Run this script in the same directory as the files. Hope this helps someone else.
i would firstly quote filename as windows typically will have spaces in the path causing problems. Also, if you are using bash or ksh you can cut a variable doing this:
fname=${filname:0:137}
using the shell instead of a utility.
Thanks for the rename command to me, but for my need it had limitations.
My requirement: Rename multiple files under a folder tree like below:
./rc5.d/S99ITMAgents1
./rc6.d/K10ITMAgents1
./rc1.d/K10ITMAgents1
./rc3.d/S99ITMAgents1
./rc2.d/S99ITMAgents1
./rc0.d/K10ITMAgents1
./rc4.d/S99ITMAgents1
All above files should get renamed, by inserting ‘old’ after “d/”.
I achieved above feat with single find command.
You should be at the parent folder of the folder tree, then it will work as below:
$ find . -name ‘*ITM*’ | xargs rename d/ d/old
$ find . -name ‘*ITM*’
./rc5.d/oldS99ITMAgents1
./rc6.d/oldK10ITMAgents1
./rc1.d/oldK10ITMAgents1
./rc3.d/oldS99ITMAgents1
./init.d/oldITMAgents1
./rc2.d/oldS99ITMAgents1
./rc0.d/oldK10ITMAgents1
./rc4.d/oldS99ITMAgents1
It worked! Hope it will be helpful in such complex needs.
Please feedback if any issues faced.
It is to mention, that `rename’ and `perl-rename’ are not the same thing!
rename is a part of the util-linux Package.
Heres the man-page(Arch/ util-linux 2.23.1)
dear owner this site i’m thai people can write english a bit
i have muti files start with number 3 digit and 1 char is underscore
058_เธ•เธฒเธฃเธฒเธ‡เธชเธà¸à¹€à¸˜Âšà¹€à¸˜Â….ปปป.doc
145_เธšเธฑเธ™เธ—เธถเธÂเธ‚เน‰เธà¸à¹€à¸˜Â„เธงเธฒเธภmanage1.doc
146_เธšเธฑเธÂเธ‚เน‰เธà¸à¹€à¸˜Â„เธงเธฒเธà¸.docx
147_เธšเธฑเธ™เธ—เธถเธÂเธ‚เน‰เฒเธภmanage5.pdf
149_เธšเธฑเธ™เธÂเธ‚เน‰เธà¸à¸˜à¸‡à¹€à¸˜à¸’เธภmanage2.ppt
i want to follow this
058_view.doc
145_view.doc
146_view.docx
147_view.pdf
149_view.ppt
Help me please.
From the command line, this worked for me:
find -name ‘*.lst’ -exec rename .lst a.lst {} ;
That is, I changed:
file1.lst
file2.lst
file3.lst
to
file1a.lst
file2a.lst
file3a.lst
I’m running Scientific Linux 6.
I want to rename file from model1 model2….model 50 as model100 model102…model150…I tried codes similar to above but didnt work…
Hello Adam ,
It functions up to a level
but it converts the file as photo-XXX_1.gif
Is there any way to get rid of _1 ?
Hello ,
Can anyone assist me with following replacement
avatarXXX_1.gif => photo-XXX.gif
I tried
rename -n ‘s/avatar(d+)_1.gif/photo-$1.gif’ *gif
But it didn’t work
Try:
for i in *; do mv $i photo-${i#avatar}; done
mert – This works for me:
rename -n ‘s/avatar(d+)_.*.gif/photo-$1.gif/’ *.gif
–> avatar123_1.gif renamed as photo-123.gif
–> avatar234_5.gif renamed as photo-234.gif
–> avatar4565_125.gif renamed as photo-4565.gif
It’s strange but it doesn’t function at all for me. Now time to debug what is wrong with it.
[root@test tet]# rename -n ‘s/avatar(d+)_.*.gif/photo-$1.gif/’ *.gif
[root@test tet]# ls
avatar605323_2.gif avatar605379_1.gif avatar605425_2.gif avatar605443_1.gif
avatar605336_1.gif avatar605386_2.gif avatar605427_1.gif
[root@test tet]# rename ‘s/avatar(d+)_.*.gif/photo-$1.gif/’ *.gif
[root@test tet]# ls
avatar605323_2.gif avatar605379_1.gif avatar605425_2.gif avatar605443_1.gif
avatar605336_1.gif avatar605386_2.gif avatar605427_1.gif
[root@test tet]# rename –help
call: rename from to files…
mert – are you using the “util-linux” rename utility? I am using ubuntu, and this is the details of my “rename” utility:
clive@dogmatix > which rename
/usr/bin/rename
clive@dogmatix > apt-file search /usr/bin/rename
ladr4-apps: /usr/bin/renamer
util-linux: /usr/bin/rename.ul
clive@dogmatix > dpkg -l | grep util-linux
ii util-linux 2.20.1-1ubuntu3 Miscellaneous system utilities
So if you are using an ubuntu derivate system then install the package:
clive@dogmatix > sudo apt-get install util-linux
hey if I want to rename a folder of files which have names like:
artist – album – 01 song
artist – album – 02 song
and I want to rename them to
01 – song
02 – song
how do I do this? Have been struggling to adjust the examples given here
Kind regards
rename -v ‘s/.* – .* – (dd) (.*)/$1 – $2/’
The brackets tell rename that those are portions you want to keep/reuse in the replace portion and are referenced by $1, $2, $3 etc… So in your case it keeps the 2 digits “(dd)” as $1 and then a space and then everything else “(.*)”.
It will then in the second part of the regex rename the file as dd – .*
i.e. 01 – song, 02 – song, 03 – song etc…
The date of my phone was reset to 2009 some day after removing the battery and I just set the time. So after some weeks I uploaded my fotos to my PC and got all the pictures with the wrong date as a file name. Here is the script that corrected that issue at once:
Please make a backup before you use it. This comes without any warranties of course.
Anyone remember about brace expansion?
mv file.{foo,bar}
will expand to:
mv file.foo file.bar
Or in a loop:
# removes the foo extension before the expansion:
for file in *.foo; do mv ${file%foo}.{foo,bar}; done
A lot less involved than some of the examples here.
@Ethan
I did something similar. After I converted my daugther’s shows for her touchpad the old avi extension where still in the filename, which I had/wanted to remove.
The touchpad doesn’t have `rename` so this is what I did…
#!/bin/sh
find . -name ‘*.mp4’ >> /tmp/$$
while read line; do
foo=`echo $line | sed s/.avi//g`
mv $line $foo
done < /tmp/$$
rm /tmp/$$
@Michael
rename ‘s/(.*).(.*).(d+)/$1.$3.$2/’ *.[0-9]
@Michael
Hi there. Would love some help on this:
img.jpg.1
img.jpg.2
img.jpg.3
to become…
img1.jpg
img2.jpg
img3.jpg
Thank you for any suggestions!
Copy one source file to different file name.
#!/bin/bash
FOLDER_PATTERN_LIST=folder_pattern_list
echo “$(cat $FOLDER_PATTERN_LIST)” | while read line; do
LISTLINE=”${line}”
echo “cp test.pdf $LISTLINE”
done
Output:
cp test.pdf File1
cp test.pdf File2
cp test.pdf File3
For FreeBSD, the syntax is slightly different:
will replace oldtext with newtext in all files of type ext
will replace spaces with underscores
s/in all files/in the names of all files/g
doh
How to add a prefix to original file names..
eg: moon.jpg –> Pic_moon.jpg
flowers.jpg –> Pic_flowers.jpg
..
rename ‘s/(.*).jpg/Pic_$1.jpg/’ *jpg
Or if you files don’t have spaces in the names you could also do:
for files in *jpg; do mv “$files” “Pic_$files”; done
my trials to rename files from pic_1.jpg pic_2.jpg … to pic_1500.jpg 1501.jpg … failed 🙁
Hope to get some help
rename -n ‘s/pic_(d+)/”pic_” . ( $1 + 1500 )/e’ *.jpg
Thanks for trying to help me. If I do:
rename -n ‘s/pic_(d+)/â€pic_†. ( $1 + 1500 )/e’ *.jpg
then I get:
Unrecognized character xE2 in column 5 at (eval 1) line 1.
🙁
It works for me, what linux are you using and which version of util-linux are you using? Mine is:
user@host > lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 10.04.4 LTS
Release: 10.04
Codename: lucid
user@host > dpkg -l | grep util-linux
util-linux 2.17.2-0ubuntu1.10.04.2
The other thing to make sure is that the quotes are exactly as I used, single quotes (‘) to enclose the whole command and double-quotes (“) to enclose the pic_ part.
Hi Sakiwi,
it’s working now 🙂 Indeed the double-quotes were the problem. I didn’t know that there are different kinds of double-quotes existing in the world.
â€pic_â€
“pic_”
Many Thanks and best regards, zaphod !!!
Glad it is working for you now, and glad I could help.
Regards
SaKiwi
Thanks for the info.
rename doesnt seem to be recursive
For recursive do this, to rename .html to .htm.bak. Replace . with your dir name if you want to replace files not in current directory
find . -name “*.html” | xargs rename .html .htm.bak
Well god points, but how about this :
rename muiltiple files in subfolders… (.nfo to movie.nfo )
“Figure 03-01-02: GradeBook class declaration with one method: Createing a Gradebook object an calling its displayMessage method.avi”
How can we bulk rename files like this? These are located in subfolders like
“Blaa: blaaaaah: bla bla: bla” etc.
None of the posted above methods not working. 🙁
I need replace all these stupid “:”.
i=0; for image in *.jpg; do mv “$image” “Name with spaces `printf “%.3d” $i`.jpg”; ((i++)); done
Renames:
asdlkjas.jpg
reojsd.jpg
asfkjdf.jpg
to
Name with spaces 000.jpg
Name with spaces 001.jpg
Name with spaces 002.jpg
Hey,
Thanks for the tip, but the rename command didnt work on my Fedora 15 x64. I didnt get any error message, but the spaces didnt go ! As one suggested above, does it work only on debian systems ? I checked man rename, there is no info on usage. Just has description of the -v switch. I am using “rename (util-linux 2.19.1)”
Thanks !
You need to use rename.pl. See comment above: http://www.cyberciti.biz/tips/renaming-multiple-files-at-a-shell-prompt.html#comment-148758
@paxpacis-Appreciate your input. however, I don’t think I understand your solution. Here are some example files:
AF_DD2795_199905_20110824.txt should be renamed to DD2795_199905_20110824_AF.raw
AF_DD2795_199905_20110924.txt should be renamed to DD2795_199905_20110924_AF.raw
How do I automate this?
This is a very usefule and informative thread. However, i haven’t quite got exactly how how I would do my renaming. I need to rename daily files from format
XX_AA1234_201109.txt to AA1234_201109_XX.ext. Note that I need to change both position of a string and the extension itself. Any suggestions would be highly appreciated!
@Gary
rename XX_ “” *.txt; rename .txt _XX.ext *.txt
@VIVEK
I think your example about the AXEL-CRAZYFROG.mp3 file is not correct. The – will not be added with your code. I think you forgot to include the hypen in the original name.
Hi, I am trying to rename some files with .ext to ones without .ext in RedHat 5
For eg: files like “ocean_11h20110906.txt” have to renamed as “ocean_11h20110906”
tried almost all the commands mentioned above. i have several such files to be renamed without extensions. Can anyone help me out. Plz treat this as urgent.
You need to use rename.pl. See comment above: http://www.cyberciti.biz/tips/renaming-multiple-files-at-a-shell-prompt.html#comment-148758
On OSX I didn’t have rename handy, so I came up with this to change extensions of a bunch of files:
find . -name “*.ext1” | sed s/ext1// | xargs -I % mv %.ext1 %.ext2
I imagine it could be done in a more simple fashion, but it works well if you need to swap something at the end or the beginning of the filenames.
Very Helpful. Thank You 🙂
$ rename .bak .txt *.bak – command worked for me to rename all *.bak to *.txt
Many Thanks
Excellent write up!!
Thank you sir…
Been browsing the internet for a while for this, and just came across this neat little command, instead of people writing different scripts and such.. AWESOME!!
hi, I need to add a letter into file name in many files but not using automator, is it possible?
for example: I have files like 1.png, fs.png, ghasd.png and need to add “-hd” so the name will be 1-hd.png fs-hd.png, and original files will be not deleted, how to do that? 🙂 thanx!
you can do the following:
# rename .png -hd.png *.png
How about that? 🙂
Let me know if you need any further help
thank you, I will try 🙂
wow this is a popular post for good reason. I wonder if its still active.
Can this descend in to directories? I’d like to rename some image files with the following file and directory structure.
01/01-0012.jpg
01/01-0342.jpg
02/02-3495.jpg
…..
98/34-0424.jpg
so i would like to rename them to
01/01-001.jpg
01/01-034.jpg
02/02-349.jpg
…..
98/34-042.jpg
So i really just want to cut the last number before the .jpg but the files literally span 99 directories, so don’t want to do it for each one. Any ideas?
Im writing my own script to rename my mp3 collection, and i want to remove all junk from the filenames:
Is it possible to check if a filename starts with numeric digits?
Cause now it remove all the first characters till –
But i only want it remove (ONLY!) numeric characters till –
i.e.
if filename starts with 09; then do; etc 🙂
Another thing is how to remove (*_bpm) where * = a wildcard, i.e 120, 59 etc.
This what i’ve made so far:
I also want include this:
willem versus wca feat wasd – hello world (radio)
willem_vs._wca_ft.wasd-hello_world-(radio_edit)
So i can as much items to change as i want.
Hope someone can help me out! 🙂
Im sick and tired of using windows based tools in wine to do this, while bash is even stronger and more fun to learn 😉
using this command:
i=1
for j in *.jpg; do mv “$j” “$i.jpg” ;(( i++ )); done
How would I get the system to add a 0 when using single digits? So instead of having the results being
_00.jpg, _1.jpg, _2.jpg, etc…….
it would return
_00.jpg, _01.jpg, _02.jpg, etc…
if rename didn’t work for you, then use this:
for file in *; do if [ -f $file ] ; then name=${file%.*}; mv $file ${name}; fi ; done
This only removes *.mp3 🙁
Ok,
I want to check if a file starts with numbers, i.e.:
101-howdy-832.mp3 -> howdy-832.mp3 ->
10-willem-hello-(radio_edit).mp3 -> willem-hello.mp3
and if it does remove it.
Any tips?
how to rename -file to file?
I would like to use the script but use strings.
For example i have:
rename s ‘/text/Text/’ *
this checks all files for have the name text in it and renames it to Text.
If i put it in a script:
#!/bin/bash
#rename script
rename ‘s/text/Text/’ *
it works at the following way: $./rename.sh
As i want to fill in what file to rename i want to use the script as following:
$./rename.sh text Text
can somebody help me out how to use variables.
Thnx!
Adjust this with your script and then try –
#!/bin/bash
match=$1
substitute=$2
rename ‘s/’$match’/’$substitute’/’ *
Then Run-
$./rename.sh text Text
gal02_1024-768_tcm251-138878.jpg
gal03_1024-768_tcm251-138882.jpg
gal04_1024-768_tcm251-138886.jpg
gal05_1024-768_tcm251-138890.jpg
gal07_1024-768_tcm251-138898.jpg
How to rename these files as 1.jpg 2.jpg….
Backup files before running above code.
In this command:
i=1
for j in *.jpg; do mv “$j” “$i.jpg” ;(( i++ )); done
How would I get the system to number as _00.jpg, _01.jpg, _02.jpg etc……
instead of _00.jpg, _1.jpg, _2.jpg, etc…..
?
Note spaces are easily done using rename.
For example
rename ” ” “_” *.mp3
rename “s/ *//g” *.mp3 as per the original example of the OP does not work for me.
Why?
In a directory we have two files a1a and a2b.
rename a. a a*
rename ‘s/a./a/’ a*
where . represents wildcard “one character”
The expected result should be aa and ab by stripping the numeric character 1 and 2 from the file name.
Neither is working under GNOME Terminal 2.30.1
Why?
Didn’t worked for me. My file name consists spaces 🙁
Like,
Report July 2010.xls
thanks…, good information
cat OPs_taste_in_music > /dev/null
strAlan: rename’s probably not the best here, try:
What if I have a bunch of files with no extension and I want to add an extension to them? I tried:
rename * *.mp3
rename * .mp3 *
rename * .mp3
but I keep getting a Bareword error 🙁
thx!
what if i have a load of files named differently(all .jpg) and i want to rename them into a sequence caleld for example ( test001.jpg test002.jpg and so on )? cheers
I want to rename files and folder like:
test .txt—–>test.txt
text1 .xls—-> text1.xls
“folder1 ” —->>folder1
“folder2 “—–>>fodler2
Actually there are some files and folders in windows which has blank space at the end of file and folder name.
Basically I want to remove blank space at the end of each file and folder.But there are some different extension files as well.
Nobody has ever asked this question online it seems…
Problem: Stupid MAC (which I dont have anymore named files with these characters:
“:â€
“?â€
etc.. in the file names.. I could not find any file renamer that would rename these files in Windows/DOS..
So I tried FENDORA linux and I can rename the manually one by one but i have hundreds…
HELP!!!!
No RENAME or mv command works.. I trired everything i can find online..
I tried specifing the “:†like this “:†“x3a†etc.. and nothing.
does anyone know how to strip these retardted OS-illegal characters out of the names.. in one shot.?
I know the ren command in DOS.. but I have no clue it seems in Linux.
and no i don’t have a mac or access to one..
Thanks ahead of time, for your help.
rename ‘s/[^[:print:]]/_/g’ *txt
This will replace all ‘non-printable’ characters in the name with and underscore.
Or if that does not work try escaping the character, e.g:
rename ‘s/?/_/g;s/:/_/g’ *.txt
rename ‘s/konstantin/georg/’ konstantin.bcn*
hello does somebody knows how to rename the following??
from:
konstantin.bcn
konstantin.bcn0
konstantin.bcn1
konstantin.bcn2
to
georg.bcn
georg.bcn0
georg.bcn1
georg.bcn2
thanks a lot in advance!!
konstantin
j=1
for i in *.txt
do
mv $i file$j.bak
j=`expr $j + 1`
done
how can I rename in specified directory only ?
filename.extension? -> filename.extension
(I have downloading script, but after pasting filename in windows codepage all extensions are finished with �?� and windows see filename garbled..)
how can I rename in specified directory only ?
filename.extension? -> filename.extension
(I have downloading script, but after pasting filename in windows codepage all extensions are finished with “?” and windows see filename garbled..)
so :
for i in *.txt.gz; do mv $i `echo $i |cut -c1-23,30-55` ; done
abd now his one :
AAAAAAB0020090617173034173034AAAA21_-_0001329515.txt.gz
into
AAAAAAB0020090617173034AAAA21_-_0001329515.txt.gz
anyone?
oh yeah,i forgot…
example :
addedit.png;1 filesave.png;1 publish_r.png;1
addusers.png;1 folder_add_f2.png;1 publish_x.png;1
apply_f2.png;1 folder_add.png;1 publish_y.png;1
and want to convert to :
addedit.png filesave.png publish_r.png
addusers.png folder_add_f2.png publish_x.png
apply_f2.png folder_add.png publish_y.png
I have a lot of .png file with extension “*.png;1” but I want to rename all in time to “*.png” how to do that?
Thanks 🙂
how can we rename 100 files in folder
1 fooo1.txt
2 fooo2.txt
3 fooo3.txt
….
to :-
1fooo1.txt
1fooo2.txt
1fooo3.txt
…….
It seems to be a Debian vs. other distros issue. Debian uses prename, perl rename, which it maps to /usr/bin/rename. I found the source for one version of perl rename online at http://www.cyberciti.biz/files/perl/rename.pl.txt and using that, my regex above works as desired.
Henry, this is an incredibly useful tip, thanks a lot. I was bashing my head against a wall trying to figure out why rename on one machine worked but not on another. I uploaded my ubuntu prename to ~/bin on my centos machine and it “just worked”.
I’m very grateful, could have spent hours trying to figure that out! 🙂
Cool one… Thanks a lot… Good job… Keep this good work going 🙂
Example file name: 2001DODGE3500546424-10_12_1.JPG
Desired file name: 2001DODGE3500546424-10.jpg
Command:
rename "s/(_[0-9]+)+.JPG/.jpg/" *.JPG
Henry,
Thank You! I’m on Opensuse 11 and this was driving me crazy… I couldn’t figure out if it was my expression or what was going on. I copied the perl file you linked to and put it in my /bin/ folder and set it to executable permissions.
Then I called
/bin/rename ‘s/(_[0-9a-z]{32})+.jpg/ .jpg/’ *.jpg
Original File: 321-646-001_01_5f81f62b4b8f448ff50eb0788aa628c7.jpeg
New File: 321-646-001_01.jpg
This is just what I needed. I’m using Google Page Speed Firefox Add-On in combo with Firebug to download Optimized versions of all of my sites images. Google rather annoyingly renames all the files and adds a _ character plus a 32 digit alpha numeric string and then changes the extension to .jpeg for .jpg files. This is just the fix that I was looking for.
Thanks Google and Thanks Henry too.
My rename doesn’t seem to support regexes. Fedora 10. How can I get this version?
# rename -V
rename (util-linux-ng 2.14.1)
It should work 2.13 was around for sometime and 2.14 is latest. Can paste your example here..
How about:
rename ‘s/-*//’ *.mp3
Hopefully that should remove everything after the first hyphen. It’s a guess though, try it on a small sample first 😉
Paul.
This rename ‘s/-*//’ *.mp3 did not work for me… Can you please tell me why it didn’t?? Also, Could you please suggest if there is any approach for this…
it follows perl rules.
What you need to do is to tell it:
rename “s/-.+/.mp3/” *.mp3
The dash will register as it should. The stop right after the dash signifies a single character. The plus after that means “one or more of the previous thing”
to test it, you don’t need to create a new file, just put -n right after rename like this:
rename -n “s/-.+/.mp3/” *.mp3
Thanks for all the tips. Can you help mi with this specific example? I have files named:
latinum_20080101_0305-200272-93930-2-25.mp3
latinum_20080101_0310-200279-93934-2-25.mp3
latinum_20080101_0315-200671-94112-2-25.mp3
and I want to rename them to get the following:
latinum_20080101_0305.mp3
latinum_20080101_0310.mp3
latinum_20080101_0315.mp3
How can I do that using rename? (I have several hundred of files like that.)
Hey even I’m working on this kind of renaming. Did the solution provided worked for you?? It didn’t worked out for me. Please let me know how have you done it.
Thanks!
A little late , but here goes:
removes everything after the dash and before the .mp3 (dash included)
rename 's/foo(.*).a/xxx$1.avi/' *.a
the (.*) in the round brackets creates a reference that you can use in the name as $1.
you can have more than one match.
rename 's/foo/xxx/' foo*.a
Thanks…
but how i can rename
foo1.a,foo2.a,…,foo10.a
To
xxx1.a,xxx2.a,….,xxx10.a
???
thanks again
rename “s/foo*/bar/g” *.a
Renames any file with an .a extension that contains “foo” to “bar” in the directory.
thanx a ton……its amazing, i though linux dont hav rename……but does.
Thanks! Did help a lot!
Wow, thank you!
I knew only the crapy mv method, i never thought that linux has a “rename”. 😛 Thanks! 🙂
Perfect!!
You can also use the standard input to find in a folder structure like:
find . -name *exp_to_find_in_folders* | rename "s/exp_to_find_for_replacement/exp_to_replace/"
leopinzon’s command didn’t worked for me. I used this one:
find -name '*exp_to_find_in_folders*' -exec rename "s/exp_to_find_for_replacement/exp_to_replace/" {} ;
The ‘rename’ command seems not working for me.. 🙁
“TRY THIS ONE”
WOW….
OH MY GOD ,IT REALLY WORKS
I CAN’T BELIVE THIS….
Very Good job dude with that examples.. was helpfull thanks