user3207230
user3207230

Reputation: 597

Add leading 0 to integer in bash after doing arithmetic

I want to always have 2-digit outputs (e.g., 03, 94):

i=1; ls | while read l; do mv "$l" name$i; let i=$i+1; done

For instance, setting i=01 and doing an addition may not return a 2-digit output.

How do I solve this problem?

Upvotes: 0

Views: 73

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 207465

I would recommend rename, a.k.a. Perl rename to you.

rename --dry-run -N "01" '$_=$N' *

Sample Output

'file-a' would be renamed to '01'
'file-b' would be renamed to '02'
'file-c' would be renamed to '03'
'file-d' would be renamed to '04'
'file-e' would be renamed to '05'
'file-f' would be renamed to '06'
'file-g' would be renamed to '07'
'file-h' would be renamed to '08'
'file-i' would be renamed to '09'
'file-j' would be renamed to '10'
'file-k' would be renamed to '11'
'file-l' would be renamed to '12'
'file-m' would be renamed to '13'
'file-n' would be renamed to '14'

If that looks good, run it again without the --dry-run option to actually rename files.

This has the following benefits:

  • It will not clobber any files whose new names would clash,
  • you can call it with --dry-run to check what it would do, without actually doing anything,
  • your new name can be as complicated a Perl expression/program as you like,
  • it will rename across directories and create any intermediate directories as necessary, if you add the -p switch

Note: Install on macOS with homebrew:

brew install rename

Upvotes: 0

tripleee
tripleee

Reputation: 189387

The printf command lets you specify number formatting with padding to a specified width. As already noted in comments, using ls is unnecessary and even harmful here.

i=1
for l in *; do
    printf -v new "name%02i" "$i"
    mv "$l" "$new"
    let i=$i+1
done

Upvotes: 2

Aman Gupta
Aman Gupta

Reputation: 440

for i in 0{7..9} {10..12}; do echo $i; done

I think it will help you

Upvotes: -1

Related Questions