Rename multiple files in bash
10,198
Solution 1
How about
rename 's/(.*).js/_$1/' *.js
Check the syntax for rename on your system.
The above command will rename A.js
to _A
& so on.
If you want to retain the extension, below should help:
rename 's/(.*)/_$1/' *.js
Solution 2
Assuming you still want to keep the extension on the files, you could do this:
$ for f in * ; do mv "$f" _"$f" ; done
It will get the name of each file in the directory, and prepend an "_".
Related videos on Youtube
Author by
andPat
Updated on September 18, 2022Comments
-
andPat over 1 year
I have
A.js
,B.js
,C.js
in a certain directory and I want to write a SINGLE command line in bash shell to rename these files _A, _B, _C. How can I do this?I tried
find -name '*.sh' | xargs -I file mv file basename file .sh
but it doesn't work, basename file .sh isn't recognized as a nested command-
pdu about 11 yearsWelcome to stackoverflow. Please read the FAQ and possibly whathaveyoutried.com, and then edit your question.
-
-
pdu about 11 yearsIf I understood him right, he wants to remove the file extension as well.
-
andPat about 11 yearsthank you very much! I modified the code this way: for f in * ; do mv "$f" "_$(basename $f .sh)" ; done and it works well!
-
Memento Mori about 11 years@user1703524 That's great! I was actually just about to edit the post in almost a very similar way to what you just did. Glad it's working.
-
msw about 11 years+1 because rename is a good tool. FYI, it is written in Perl so the syntax is uniform across systems search.cpan.org/~rmbarker/File-Rename-0.06/rename.PL
-
anishsane over 10 years@msw: No, the syntax may be different. I have seen syntax -
'rename "from_regex" "to_string" files_filter'
instead ofrename 's/from_regex/to_string/' files_filter