Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename Files and Directories (Add Prefix)

Tags:

linux

shell

perl

People also ask

How do you add a prefix to a file in Linux?

Add a prefix for file in *. txt; do mv "$file" "yourPrefix$file"; done; Exmpale to add an underscore "_" in front of text each file name: for file in *.

How do I rename files in bulk with different names?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I rename a file in a directory?

Right-click on the item and select Rename, or select the file and press F2 . Type the new name and press Enter or click Rename.


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)


Use the rename script this way:

$ rename 's/^/PRE_/' *

There are no problems with metacharacters or whitespace in filenames.


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 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_.


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.


If you have Ruby(1.9+)

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

with Perl:

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