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?
Asked
Active
Viewed 9,944 times
4
-
2That is actually going to be the same answer as in your other question: http://askubuntu.com/questions/659653/rename-hundreds-of-directories except you change the "mv" command there to fit your new needs. – Rinzwind Aug 10 '15 at 09:21
-
1By the way: there is a tool called "pyrenamer" where you can do this from the desktop. App: https://apps.ubuntu.com/cat/applications/saucy/pyrenamer/ (it is in Ubuntu software center) – Rinzwind Aug 10 '15 at 09: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 '15 at 09: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 '15 at 09:41
-
try pyrenamer It does an amazing job and has some nifty shortcuts for manipulating filenames – Rinzwind Aug 10 '15 at 09:52
2 Answers
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.

Falko
- 241
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

A.B.
- 90,397
-
First answer and best answer... Dunno why the other one got so many upvotes! ;-) – Fabby Aug 10 '15 at 14:20