0

On unix I have files which have been renamed as their original name follwed by _inode number (ie the file dog would be renamed dog_inodeno). I am now trying to remove the inode no so i can search for the original file name elsewhere. Does anyone know how I can do this and teh coding neccesary.

Thanks

  • I imagine that the script that renamed the files could be slightly modified to rename those back. No? – devnull Oct 03 '13 at 14:14

2 Answers2

0

This should do the job:

find . -type f -name "*_[0-9]*" -exec \
  sh -c 'for i do
    b=$(basename "$i")
    r=$(basename "$i" "_$(ls -i "$i"|awk "{print \$1}")")
    if [ "$b" != "$r" ]; then 
      echo mv "$i" "$(dirname $i)/$r"
    fi
  done' sh {} + 

Replace echo mv by mv for the script to actually rename the files.

jlliagre
  • 29,783
  • 6
  • 61
  • 72
0

The solution here will do rename your files only if the inode number of a file is part of the file's name in the mentioned format, which is what the OP wants.

Solution is successfuly tested at my end.

find ./ -name "*_[0-9][0-9][0-9][0-9][0-9][0-9]" -exec sh 'rename-files.sh' {} \;

Store the below script for the find command to be successful.

#Script Name: rename-files.sh
#!/bin/bash

#Store the result of find
find_result=$1

#Get the existing file name
fname_alone=`expr ${find_result} : '.*/\(.*\)' '|' ${find_result}`
fname_with_relative_path=`expr ${find_result} : '.\(.*\)' '|' ${find_result}`
fname_with_full_path=`echo "$(pwd)${fname_with_relative_path}"`

#Get the inode number of file name
file_inode_no=`find ./ -name ${fname_alone} -printf '%i'`

#Read the end of name
end_of_name=`echo $fname_alone | awk -F "_" '{print $NF}' ` 

#Check if end of name contains its file's inode number
if [ $end_of_name -eq $file_inode_no ]
then
   #Remove the inode number at the end of file name 
   new_name=`expr $find_result : '.\(.*\)_.*' '|' $find_result`
   #Append the path of the file
   renamed_to=`echo "$(pwd)${new_name}"` 
   #Rename your dog_inodeno to dog
   mv $fname_with_full_path $renamed_to
fi

Hope this helps.

smRaj
  • 1,246
  • 1
  • 9
  • 13