I would like to prepend numerical order form 1-777 on the orders given to it. You can loop it through and increment variable in Bash. However, I would like to do it with Zsh and/or Awk. An example follows. Filenames




OS: Debian 8.5

  • 1
    Is this a "visual" thing only (having the current number displayed when listing the files) or do you want to rename the files ? – don_crissti Dec 23 '16 at 19:21
  • @don_crissti I want to rename the files. – Léo Léopold Hertz 준영 Dec 23 '16 at 21:00
  • 2
    There's plenty of similar questions if you search rename e.g. 1, 2 so in your case autoload zmv then i=0; zmv -n '*' '$((++i)).$f' and remove the -n if you like what you see... – don_crissti Dec 23 '16 at 21:18
ls *.jpg | nl -s.

nl will add line numbers; -s. specifies a . as the separator between the number and the data (in this case, the file names). If you want to remove the leading spaces from the output, you can add this:

ls *.jpg | nl -s. | sed 's/^ *//'

sed will then remove zero or more spaces from the start of the line.

If you really want to do this with awk:

ls *.jpg | awk '{ print NR"."$0 }'

NR is an internal variable indicating the number of records thus far parsed.

To make permanent changes in filenames, do the following (Michael Vehrs)

ls *.jpg | nl -s. | sed 's/ *\([0-9]\+\)\.\(.*\)/\2 \1\.\2/' | xargs -n 2 mv
  • How can you make the changes permanent in filenames? - - I think your nl approach is outstanding. I actually did not know about the command. – Léo Léopold Hertz 준영 Dec 25 '16 at 9:43
  • 2
    You need to pipe the result to mv, like this ls *.jpg | nl -s. | sed 's/ *\([0-9]\+\)\.\(.*\)/\2 \1\.\2/' | xargs -n 2 mv. – Michael Vehrs Dec 27 '16 at 9:55

With zsh, use zmv to perform bulk renaming. First run autoload -U zmv (put this in your .zshrc), then

zmv 'IMG_*.jpg' '$((i++)).$f'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.