-2

I have bunch of files with this kind of file names and would like to rename them like this.

Current:

file_name.mt0  
file_name.mt1  
file_name.mt2  
file_name.mt3  
file_name.mt4  
file_name.mt5   
file_name.mt6  
file_name.mt7  
file_name.mt8  
file_name.mt9  
file_name.mt10  
file_name.mt11

New:

file_name.mt0000  
file_name.mt0001  
file_name.mt0002  
file_name.mt0003  
file_name.mt0004  
file_name.mt0005   
file_name.mt0006  
file_name.mt0007  
file_name.mt0008  
file_name.mt0009  
file_name.mt0010  
file_name.mt0011

Thanks in advance~~

2

A script as follows can do that:

#! /usr/bin/ksh

typeset -Z4 N
find . -name 'file_name.mt*' | while read FN
do
   N=${FN#./file_name.mt}
   mv $FN file_name.mt$N
done
  • Thanks for your post. I tried your script and I got this message. "typeset: -Z: invalid option". I'm not a script expert, so I'm looking for your help. – funfun Sep 3 '18 at 17:07
  • Oh. After I placed only your script in my run file, then it works!! Thanks a lot~~ – funfun Sep 3 '18 at 17:48
0

Larry Walls simple but powerful rename command is the right choice:

rename 's/(\d+)$/sprintf("%04d",$1)/e' file*

  • Thanks. I tried your command line in my linux shell, but nothing happens. Is it correct to have just "file*" at the end? – funfun Sep 3 '18 at 17:40
  • file* ist the glob expression for all files starting with "file". Try rename -h, it shows the help: Usage: rename [ -h|-m|-V ] [ -v ] [ -n ] [ -f ] [ -e|-E perlexpr]*|perlexpr [ files ] – ingopingo Sep 5 '18 at 7:44
  • Probably should mention that rename could be one of two tools. – Sparhawk Sep 6 '18 at 4:56
  • @Sparhawk You mention two tools, cool rename is one, and what is the other? – NiteRain Sep 7 '18 at 13:33
  • @NiteRain The other one is rename 😁. See here; people may get confused if they have the other one installed by default. – Sparhawk Sep 7 '18 at 22:36
0
#!/bin/bash

for i in file_name*; do 
    nf=`printf "file_name.mt%04d" ${i//[!0-9]/}`; 
    mv $i $nf;
done

Here is a bash script, that can do what you want. Removed the ls, and just using a glob. Good reference @Sparkhawk

  • Thanks. I ran your script where I have bunch of files with that file_name.mtxx, but only one file(file_name.mt0000) is left after running the script. – funfun Sep 3 '18 at 17:36
  • To generate test files: for i in {0..11}; do touch file_name.mt$i; done – NiteRain Sep 6 '18 at 3:46
  • Don't parse ls. – Sparhawk Sep 6 '18 at 4:55
  • @Sparhawk I guess you wanted me to use a find command? – NiteRain Sep 7 '18 at 13:40
  • 1
    @NiteRain There's a link in my previously-linked question that gives more details, but apart from using find, you could just use for i in file_name*;. – Sparhawk Sep 7 '18 at 22:38

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.