Zmv command to rename file after matching pattern

renamezsh

I was trying to figure out a solution for this question using zmv. I am unable to find an exact solution using zmv. This is what I could come up with so far.

From here, I could rename all files like 1.jpg, 2.jpg, 34.jpg etc as 001.jpg, 002.jpg and 034.jpg using the command,

zmv '(<1->).jpg' '${(l:3::0:)1}.jpg'

Now, I need to modify zmv to have some patterns in the beginning so that I can rename the files. However, I am not able to accomplish this. The closest I could find is this solution.

c=1 base='0-' zmv '*.jpg' '${base}${(l:3::0:)$((c++))}.jpg'

However, the problem with the above approach is if I have files as 0-1.jpg, 0-44.jpg, the above command will replace it as 0-001.jpg and 0-002.jpg instead of 0-001.jpg and 0-044.jpg.

How should I modify the zmv command to accomplish the renaming as desired?

Best Answer

You can use -l expansion flag:

l:expr::string1::string2:

Pad the resulting words on the left. Each word will be truncated if required and placed in a field expr characters wide.

The arguments :string1: and :string2: are optional; neither, the first, or both may be given. Note that the same pairs of delimiters must be used for each of the three arguments. The space to the left will be filled with string1 (concatenated as often as needed) or spaces if string1 is not given. If both string1 and string2 are given, string2 is inserted once directly to the left of each word, truncated if necessary, before string1 is used to produce any remaining padding.

If the MULTIBYTE option is in effect, the flag m may also be given, in which case widths will be used for the calculation of padding; otherwise individual multibyte characters are treated as occupying one unit of width.

If the MULTIBYTE option is not in effect, each byte in the string is treated as occupying one unit of width.

Control characters are always assumed to be one unit wide; this allows the mechanism to be used for generating repetitions of control characters.

Try:

zmv '([0-9])-([0-9]##).(jpg)' '$1-${(l:3::0:)2}.$3'
Related Question