[linux] Rename Files and Directories (Add Prefix)

I would like to add prefix on all folders and directories.

Example:

I have

Hi.jpg
1.txt
folder/
this.file_is.here.png
another_folder.ok/

I would like to add prefix "PRE_"

PRE_Hi.jpg
PRE_1.txt
PRE_folder/
PRE_this.file_is.here.png
PRE_another_folder.ok/

Regards,

This question is related to linux perl shell

The answer is


Thanks to Peter van der Heijden, here's one that'll work for filenames with spaces in them:

for f in * ; do mv -- "$f" "PRE_$f" ; done

("--" is needed to succeed with files that begin with dashes, whose names would otherwise be interpreted as switches for the mv command)


This could be done running a simple find command:

find * -maxdepth 0 -exec mv {} PRE_{} \;

The above command will prefix all files and folders in the current directory with PRE_.


Here is a simple script that you can use. I like using the non-standard module File::chdir to handle managing cd operations, so to use this script as-is you will need to install it (sudo cpan File::chdir).

#!/usr/bin/perl

use strict;
use warnings;

use File::Copy;
use File::chdir; # allows cd-ing by use of $CWD, much easier but needs CPAN module

die "Usage: $0 dir prefix" unless (@ARGV >= 2);
my ($dir, $pre) = @ARGV;

opendir(my $dir_handle, $dir) or die "Cannot open directory $dir";
my @files = readdir($dir_handle);
close($dir_handle);

$CWD = $dir; # cd to the directory, needs File::chdir

foreach my $file (@files) {
  next if ($file =~ /^\.+$/); # avoid folders . and ..
  next if ($0 =~ /$file/); # avoid moving this script if it is in the directory

  move($file, $pre . $file) or warn "Cannot rename file $file: $!";
}

Use the rename script this way:

$ rename 's/^/PRE_/' *

There are no problems with metacharacters or whitespace in filenames.


To add a prefix to all files and folders in the current directory using util-linux's rename (as opposed to prename, the perl variant from Debian and certain other systems), you can do:

rename '' <prefix> *

This finds the first occurrence of the empty string (which is found immediately) and then replaces that occurrence with your prefix, then glues on the rest of the file name to the end of that. Done.

For suffixes, you need to use the perl version or use find.


For adding prefix or suffix for files(directories), you could use the simple and powerful way by xargs:

ls | xargs -I {} mv {} PRE_{}

ls | xargs -I {} mv {} {}_SUF

It is using the paramerter-replacing option of xargs: -I. And you can get more detail from the man page.


This will prefix your files in their directory.

The ${f%/*} is the path till the last slash / -> the directory

The ${f##*/} is the text without anything before last slash / -> filename without the path

So that's how it goes:

for f in $(find /directory/ -type f); do 
  mv -v $f ${f%/*}/$(date +%Y%m%d)_Prefix_${f##*/}
done

with Perl:

perl -e 'rename $_, "PRE_$_" for <*>'

On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done

If you have Ruby(1.9+)

ruby -e 'Dir["*"].each{|x| File.rename(x,"PRE_"+x) }'

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to perl

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer "End of script output before headers" error in Apache Perl - Multiple condition if statement without duplicating code? How to decrypt hash stored by bcrypt Split a string into array in Perl Turning multiple lines into one comma separated line String compare in Perl with "eq" vs "==" how to remove the first two columns in a file using shell (awk, sed, whatever) Find everything between two XML tags with RegEx Difference between \w and \b regular expression meta characters

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"