Search code examples
bashsedfile-rename

Pad numerical values in filename with three digit value using sed


I am passing a filename into my bash script and cleaning the name using sed. A few sample files would be:

Test 01.txt
Test v2 01.txt

I would like to get back:

Test 001.txt
Test v002 001.txt

Here is my script

#!/bin/bash

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $@
do

j=`basename "$f" ".???"`
BASENAME=`basename "$f" ".???"`
DIRNAME=`dirname "$f"`

j=`echo $j |sed -e 's/\///g'`
j=`echo $j |sed -e 's/_/ /g'`
j=`echo $j |sed -e 's/^\.//'`
j=`echo $j |sed -e 's/\[[^()]*\]//g'`
j=`echo $j |sed -e 's/([^()]*)//g'`
j=`echo $j |sed -e 's/#//g'`
j=`echo $j |sed -e 's/+/\ /g'`
j=`echo $j |sed -e 's/\.\././g'`
j=`echo $j |sed -e 's/\&/and/g'`
j=`echo $j |sed -e 's/\ -/-/g'`
j=`echo $j |sed -e 's/-\ /-/g'`
j=`echo $j |sed -e 's/-{2,}/-/g'`
j=`echo $j |sed -r -e 's/\d+/sprintf("%03d",$&)/e'`
j=`echo $j |sed -e 's/\.\././g'`
j=`echo $j |sed -e "s/\'//g"`
j=`echo $j |sed -r -e 's/ {2,}/ /g'`
j=`echo $j |sed -e 's/\ \././g'`

if [ "$BASENAME" != "$j" ]; then
  mv -v "$f" "$DIRNAME"/"$j"
fi

done

Here is the problem line

j=`echo $j |sed -r -e 's/\d+/sprintf("%03d",$&)/e'`

The regex will work with rename but not with sed.


Solution

  • Instead of

    sed -r -e 's/\d+/sprintf("%03d",$&)/e'
    

    use

    perl -pe 's/\d+/sprintf("%03d",$&)/ge'