NerdVana

The glass is 2x larger than it needs to be

Rename files, but preserve meta-data

Written by Eric Schwimmer

I needed to rebuild some archives by renaming the files inside them, but I wanted to keep all of the other file metadata (i.e. ownership, permissions, modification time, etc) the same for audit reasons. The rename command in the util-linux package doesn't do this, so I wrote the following Bash snippet to emulate the rename command's functionality while preserving file metadata:

#!/bin/bash

[[ $# -lt 3 ]] && \
    echo "rename.sh <match pattern> <replace pattern> file [file]..." && \
    exit 1

from=$1; shift
to=$1; shift

while (( "$#" )); do
    oldFile=$1
    [[ -f $oldFile ]] || continue
    newFile=${oldFile##*/}
    path=${oldFile%/*}
    [[ $path == $oldFile ]] && path='.'
    cp -al $oldFile $path/${newFile/$from/$to} && unlink $oldFile
    shift
done


comments powered by Disqus