Ubuntu: Delete first part of file names



Question:

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?


Solution:1

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.


Solution:2

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  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »