Home > Blockchain >  How can I zero pad first instance of a number while preserving the rest of the file name with bash
How can I zero pad first instance of a number while preserving the rest of the file name with bash

Time:09-21

I have been messing with this for a while and I am stuck. I was spoiled on my laptop because I could use the perl rename and fixing number padding is simple. Now I am on a server and rename is not working. I need a way of adjusting the patting on a file that looks like the following

foo-353-03-53-23.txt 

most the examples on the this website and other will destroy all the content in the padding process which is not helpful to me as I have metadata in the filename.

I am looking for the result to produce the following

foo-000353-03-53-23.txt

Everything is preserved just the first number is padded.

Please help preserve my file names and sanity.

Thanks in advance.

CodePudding user response:

Split string and reformat:

#!/usr/bin/env bash

oldname='foo-353-03-53-23.txt'

IFS=- read -r -d '' a n b <<<"$oldname"
printf -v newname '%s-d-%s' "$a" "$((10#$n))" "${b%?}"

# Debug dump variables
declare -p oldname newname

Alternate method using Bash's Regex to capture string elmeents:

#!/usr/bin/env bash

oldname='foo-353-03-53-23.txt'

# Capture string elements with Regex
[[ $oldname =~ ([^0-9] )([0-9] )(.*) ]]

# Reformat string elements
printf -v newname '%sd%s' \
  "${BASH_REMATCH[1]}" "$((10#${BASH_REMATCH[2]}))" "${BASH_REMATCH[3]}"

if [ ! -e "$newname" ]; then
  echo mv --no-clobber -- "$oldname" "$newname"
else
  printf 'Cannot rename %s to %s, because %s already exist!\n' \
    "$oldname" "$newname" "$newname" >&2
fi
  • Related