2

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
3

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.

2
  • 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
2

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

rename 's/.{7}(\.txt)/$1/' abc*
2
  • 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
-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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