4

I have a directory full of files foo_num.txt. I'd like to rename all to num.txt (that is delete the "foo_" part). Can I do this in one line?

5
  • 2
    That is actually going to be the same answer as in your other question: askubuntu.com/questions/659653/rename-hundreds-of-directories except you change the "mv" command there to fit your new needs.
    – Rinzwind
    Aug 10, 2015 at 9:21
  • 1
    By the way: there is a tool called "pyrenamer" where you can do this from the desktop. App: apps.ubuntu.com/cat/applications/saucy/pyrenamer (it is in Ubuntu software center)
    – Rinzwind
    Aug 10, 2015 at 9:23
  • it's just that I need to move the first part of the name - not the last... does it still function then?
    – Ditte
    Aug 10, 2015 at 9:25
  • Thank you for the answer :) I can't figure out how to make it work. I guess it's too complex for me. I'll try to do it manually :( Have a nice day and thanks for trying :)
    – Ditte
    Aug 10, 2015 at 9:41
  • try pyrenamer It does an amazing job and has some nifty shortcuts for manipulating filenames
    – Rinzwind
    Aug 10, 2015 at 9:52

2 Answers 2

5

If you don't want to bother with for-loops in Bash, you might want to use the rename program:

rename "s/foo_//" *.txt

The first argument is the Perl expression defining the string replacement rule. In this case: [s]ubstitute "foo_" with "".

The second argument filters the files you want to rename.

1

As your first part is separated by a _ I suggest you

rename 's/.*?_//' *.txt

The ? means not greedy, therefore only the first occurrence of _ will be replaced.

Example

$ ls -laog
total 4280
drwxrwxr-x  2 4329472 Aug 10 13:05 .
drwx------ 55   20480 Aug 10 12:54 ..
-rw-rw-r--  1       0 Aug 10 13:05 foo_1_1.txt
-rw-rw-r--  1       0 Aug 10 13:05 foo_2_2.txt
-rw-rw-r--  1       0 Aug 10 13:05 foo_3_3.txt

$ rename 's/.*?_//' *.txt

$ ls -laog
total 4280
drwxrwxr-x  2 4329472 Aug 10 13:06 .
drwx------ 55   20480 Aug 10 12:54 ..
-rw-rw-r--  1       0 Aug 10 13:05 1_1.txt
-rw-rw-r--  1       0 Aug 10 13:05 2_2.txt
-rw-rw-r--  1       0 Aug 10 13:05 3_3.txt

To replace all occurrences use

rename 's/.*_//' *.txt

Example

$ ls -laog
total 4280
drwxrwxr-x  2 4329472 Aug 10 13:08 .
drwx------ 55   20480 Aug 10 12:54 ..
-rw-rw-r--  1       0 Aug 10 13:08 foo_1_1.txt
-rw-rw-r--  1       0 Aug 10 13:08 foo_2_2.txt
-rw-rw-r--  1       0 Aug 10 13:08 foo_3_3.txt

$ rename 's/.*_//' *.txt

$ ls -laog
total 4280
drwxrwxr-x  2 4329472 Aug 10 13:09 .
drwx------ 55   20480 Aug 10 12:54 ..
-rw-rw-r--  1       0 Aug 10 13:08 1.txt
-rw-rw-r--  1       0 Aug 10 13:08 2.txt
-rw-rw-r--  1       0 Aug 10 13:08 3.txt
1
  • First answer and best answer... Dunno why the other one got so many upvotes! ;-)
    – Fabby
    Aug 10, 2015 at 14:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .