0

I am in need of some command line fu.

I have a wack of files, starting with 4 numbers then a dash then various letters then extentsion, eg.

0851_blahblah_p.dbf
0754_asdf_l.dbf

What I want is to move the four numbers to the end of the filename (keeping the extension in tact) and remove the underscore. Thus the above example would be renamed:

blahblah_p0851.dbf
asdf_l0754.dbf

All help is appreciated.

I am running ubuntu.

Thanks DJ

paddleman
  • 255
  • 2
  • 11

3 Answers3

3

Here is a solution in pure bash:

for file in *.dbf; do 
    ext=${file##*.};num=${file%%_*};name=${file%.*};name=${name#*_}
    mv $file $name$num"."$ext; 
done

Broken down with comments:

for file in *.dbf
do 
    ext=${file##*.}              # Capture the extension
    num=${file%%_*}              # Capture the number
    name=${file%.*}              # Step 1: Capture the name
    name=${name#*_}              # Step 2: Capture the name
    mv "$file" "$name$num.$ext"  # move the files to new name
done
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
2

You can use the rename command:

rename 's/([0-9]{4})_([[:alpha:]]*)_.*.dbf/$2_$1.dbf/' *
gturri
  • 13,807
  • 9
  • 40
  • 57
1

You can use sed also

$sed -r 's/([^_]+)_([^.]+)/\2\1/g'

Using this way the given name is splitted and modified as per your requirement.

(or)

Use this script and pass the file names as argument it will move the file name as per the requirement.

 #!/bin/sh  
 if [ $# -ne  1 ] ; then
   echo "Usage : <sh filename> <arguments>"
   exit ;
 fi
 for file in $*
 do
    mv $file `echo $file | sed -r 's/([^_]+)_([^.]+)/\2\1/g' `
 done
Kalanidhi
  • 4,902
  • 27
  • 42