Geo
Geo

Reputation: 15

Rename files into numbers, starting with a specific number

I want to rename all files in a directory to be sequential numbers:

1.txt
2.txt
3.txt

and so on...

Here's the code I'm currently using:

ls | cat -n | while read n f; do mv "$f" "$n.txt"; done 

The code does work, but I need to start with a specific number. For example, I may want to start with the number 49 instead of the number 1.

Is there any way to do this in terminal (on a Mac)?

Upvotes: 0

Views: 959

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52132

You could use something like nl with the -v option to set a starting line number other than 1, but instead, you can just use Bash features:

i=1
for f in *; do
    [[ -f $f ]] && mv "$f" $((i++)).txt
done

where i is set to the initial value you want.

This also avoids parsing the output of ls, which is recommended to avoid. Instead, I use a glob (*) and a test (-f) to make sure that I'm actually manipulating files and not directories.

Upvotes: 4

Related Questions