-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~~

Siva
  • 9,077
funfun
  • 99

3 Answers3

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 03 '18 at 17:07
  • Oh. After I placed only your script in my run file, then it works!! Thanks a lot~~ – funfun Sep 03 '18 at 17:48
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

NiteRain
  • 308
0

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

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

ingopingo
  • 807
  • 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 03 '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 05 '18 at 07:44
  • Probably should mention that rename could be one of two tools. – Sparhawk Sep 06 '18 at 04:56
  • @Sparhawk You mention two tools, cool rename is one, and what is the other? – NiteRain Sep 07 '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 07 '18 at 22:36