Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell/Bash shortcut for bulk renaming of files in a folder

Is there a shortcut in Shell/Bash that can rename all the files in a folder based on a regex or some other criteria. What I am looking for here is in my folder documents, that has let's say a 100 text files with the following naming convention:

<longdocumentidentifier>-doc-<counter>.txt. 

I need to rename all the files with the above given convention to just:

doc-<counter>.txt 

Is there a one-liner that can help me with the above?

like image 987
sc_ray Avatar asked Dec 07 '11 14:12

sc_ray


People also ask

Is there a way to rename a bunch of files at once?

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.


2 Answers

I would suggest something like this:

for i in *-doc-*.txt; do mv "$i" "${i/*-doc-/doc-}"; done 

${i/*-doc-/doc-} replaces the first occurrence of *-doc- with doc-.

If you need to do more than one replacement (see comment number 1), you need to use the ${var//Pattern/Replacement} variant. If you need to replace the beginning of the name you need to use ${var/#Pattern/Replacement}, if you need to replace the end (ie: the extension) you need to use the ${var/%Pattern/Replacement} form.

See Shell Parameter Expansion for more details. This expansion is bash specific.

like image 152
Sorin Avatar answered Sep 22 '22 06:09

Sorin


If you have rename then, rename 's/^.*-doc-/doc-/' *.txt should do the trick.

like image 24
telenachos Avatar answered Sep 22 '22 06:09

telenachos