简体   繁体   中英

Rename all files in a folder

I'm on a linux, and a download a lot of funny pictures. Unfortunately, I'm left with a bunch of duplicate names like download (1) and image.jpeg . I would like to change them all to something a bit more helpful.

Is there a way to (preferably using bash) to rename all files to sequential 4 digit numbers with leading zeroes?

Eg:

0001
0002
0003
0004
....

The code snippet provided in the previous answer, is an elegant way of doing it but a typo or a shell incompatibility may cause it not to function properly.

please try the code below instead. It does the same thing but every shortcut has been explicitly written with debugging echo commands in the loop.

counter=1
cd /my/image/directory
for f in $(ls -1)
do
  new_filename=$(printf "%04d" ${counter})     
  echo "renaming ${f} ..to.. ${new_filename}"
  mv ${f} ${new_filename}
  (( counter=${counter}+1 ))
done

the screen output will be a little chatty. if you have too many files, you might want to add | tee screen.out | tee screen.out to the end of the line with done command. So that you can go back and see what happened to which file recorded in the screen.out.

I created my own tool to do this . It also maintains file extensions, which I did not mention, but should probably be included. Here is the code:

#!/bin/sh

dir=$1
cd $dir
echo "Renaming all files in $dir."
COUNTER=1
for i in `ls -1`
do
  extension=${i##*.}
  mv "$i" "$COUNTER.$extension"
  echo "$i ==> $COUNTER.$extension"
  COUNTER=$(expr $COUNTER + 1 )
done

It does not (at the time of writing) include the leading zeroes, but it gets the job done.

As long as you don't care which file is renamed to what, it's easy :)

counter=1
for f in *; do
    mv "$f" "$( printf "%04d" $((counter++)) )"
done

尝试使用后缀.bash将所有文件重命名为文件夹中的后缀.sh很容易完成

rename .bash .sh *.bash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM