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

Share:
10,198

Related videos on Youtube

andPat
Author by

andPat

Updated on September 18, 2022

Comments

  • andPat
    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
      pdu about 11 years
      Welcome to stackoverflow. Please read the FAQ and possibly whathaveyoutried.com, and then edit your question.
  • pdu
    pdu about 11 years
    If I understood him right, he wants to remove the file extension as well.
  • andPat
    andPat about 11 years
    thank 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
    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
    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
    anishsane over 10 years
    @msw: No, the syntax may be different. I have seen syntax - 'rename "from_regex" "to_string" files_filter' instead of rename 's/from_regex/to_string/' files_filter