Change some file names (prefix to postfix)

filenamesfilesrenamesuse

I have a directory containing thousands of files with names
t_00xx_000xxx.png and 00xx_000xxx.png. I want to change the names of the files which starts with t_, like t_00xx_000xxx.png to 00xx_000xxx_t.png

So take the prefix and put it as a postfix for some of the files. Can this be done in only one command?

I am running on SUSE SLES12 SP2.

Best Answer

This will work if we assume everything up to the first underscore to be the prefix.

for f in *.png; do
    new=$(echo "$f" | sed -r 's/^([^_]*)_(.*)\.(.*)$/\2_\1.\3/');
    echo "Renaming: $f => $new";
    #mv $f $new
done

Remove the # in front of mv if you're happy with the output.


With prename it would be a little easier:

prename -n 's/^([^_]*)_(.*)\.(.*)$/$2_$1.$3/'

If t_ is always the prefix, change to this pattern:

for f in t_*.png; do
    new=$(echo "$f" | sed -r 's/^t_(.*)\.(.*)$/\1_t.\2/');
    echo "Renaming: $f => $new";
    #mv $f $new
done
Related Question