Batch rename files by shell

·

1 min read

Today I have a lot of screenshot images need to be rename. Well , it seems to be an easy task, but the space characters inside file names cause a little trouble.

If I define a bash function in command line directly, it works well:

cnf(){
files=$(ls -r -t *2021-06-11*.png)
for file in $files
do
echo "$file"
done
}

But if I put them in a bash script, the for loop will run into problem because it treat space characters as field separator:

#!/bin/bash
files=$(ls -r -t *2021-06-11*.png)
a=0
for file in $files
do
let a=a+1
echo "$file"
done

I find the best way(to me ...) is change $IFS(internal field separator) like this:

#!/bin/bash
IFS=$'\n'
files=$(ls -r -t *2021-06-11*.png)
...

I also try to use "find" to replace "ls", but in my mac (bsd version find), it is hard to sort files by its modification time, so I choose "ls -t -r" .

Before changing $IFS, I've tried another way: use "tr" to replace space character to something (ex: underscore) to make for loop works, and then change back to space character in rename command. A little bit ugly, but works too.