I have hundreds of file andI want to remove last 7 characters from the filename but keeping its extension.

Old name:

abc_xyz12_4567.txt

abcde_xyz12_4567.txt

New name:

abc_xyz.txt

abcde_xyz.txt
share|improve this question
up vote 3 down vote accepted

try

ls | awk -F. '{printf "mv %s %s.%s\n",$0,substr($1,1,length($1)-7),$2 ;}' | ksh

you can use

ls | awk -F. '{printf "mv %s %s.%s\n",$0,substr($1,1,length($1)-7),$2 ;}'

to have a preview.

share|improve this answer
1  
(assuming the file names contain only one dot and no shell special characters). – Stéphane Chazelas Sep 10 '14 at 10:32
    
for spaces in the files use ls | awk -F. '{printf "mv \"%s\" \"%s.%s\"\n",$0,substr($1,1,length($1)-7),$2 ;}' | ksh – nils petersohn Sep 20 '16 at 20:38

You can use rename (Or prename in some OS):

rename 's/.{7}(\.txt)/$1/' abc*
share|improve this answer
    
rename sometimes goes as prename (perl-rename), depending on the specific OS (there is another command called rename, which uses a more tr-like syntax and is generally inferior). – evilsoup Sep 10 '14 at 12:48
    
@evilsoup: Yes, added that note. – cuonglm Sep 10 '14 at 12:51

with GNU tar:

touch abc_xyz12_4567.txt abcde_xyz12_4567.txt
tar --remove-files --xform='s/\(.*\).\{7\}\./\1./' -c ./* | tar -x
ls

OUTPUT

abcde_xyz.txt  abc_xyz.txt

That will do it all safely - and in fact you don't even need the --remove-files option - you might instead untar the files to a different directory and verify the filename change worked. Maybe like:

tar --xform... | tar -C ../test -x
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.