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 1.0k times
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
- 2
- 10
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.
- 92,125