Thursday, February 3, 2022

[SOLVED] Replace digits in a string by a pattern containing the number of replaced digits

Issue

I am trying to replace a number consisting of n digits in a filename by a pattern like %03ld or %04ld respectively (depending of the number of digits).

For example:

  • "img/img_000.png" -> "img/img_%03ld.png"
  • "RA20190201_A/img_1030.tif" -> "RA20190201_A/img_%04ld.tif"
  • ".../SomeImage_z004.tif" -> ".../SomeImage_z%03ld.tif"

As you can see

  • the number does not always consist of 0s only
  • it is always followed by the file extension (which can vary)
  • the path can contain other numbers which are not relevant (and must remain unchanged)

I think this could be done easily using python (or other languages) but I'm trying to do it by a one-liner with linux build-in tools like awk or sed using pipes.

I was able to count the digits using awk s function gsub:

> echo "9001_bla/img_0001.png" | awk '{print gsub(/[0-9]/, "")}'
8

But I haven't managed to isolate the counting on the relevant part and to perform the actual replacement.

How can I achieve this?


Solution

One way of doing it in awk

awk 'BEGIN {
  FS=OFS="."
}
match($(NF-1),/[0-9]+$/) {
  $(NF-1)=(substr($(NF-1),1,RSTART-1) "%0" RLENGTH "ld")
} 1'


Answered By - oguz ismail
Answer Checked By - Gilberto Lyons (WPSolving Admin)