Bash script copy rename multiple files

In this tutorial, I am written a small program with “Bash script copy rename multiple files” on Linux. Linux the essential for DevOps Roles.

The syntax for the loop

for file in $(ls)
do
       cp $file ${file/<Pattern>/<Replacement>}; 
done

For example, I will copy and rename 2 files “foo2017-2.txt and foo2017-3.txt” into “foo2018-2.txt and foo2018-3.txt”  in “folder” folder.

[huupv@huupv devopsroles]$ pwd
/home/huupv/devopsroles
[huupv@huupv devopsroles]$ ls folder/
file.txt foo2017-1.txt foo2017-2.txt foo2017-3.txt
[huupv@huupv devopsroles]$

My Bash script copy rename multiple files

#!/bin/bash
#Only 2 copies files from the bottom and change 2017 to 2018

FOLDER=$1;
for file in $(ls $FOLDER/ | tail -n2)
do
   cp ${FOLDER}/${file} ${FOLDER}/${file/2017/2018};
done

Execute bash script

[huupv@huupv devopsroles]$ chmod +x bash_rename_files.sh
[huupv@huupv devopsroles]$ ./bash_rename_files.sh /home/huupv/devopsroles/folder

The result, after you run the bash script

[huupv@huupv devopsroles]$ ls /home/huupv/devopsroles/folder/
file.txt foo2017-1.txt foo2017-2.txt foo2017-3.txt foo2018-2.txt foo2018-3.txt
[huupv@huupv devopsroles]$

The screen output terminal

Bash script copy rename multiple files

Conclusion

Thought the article, How to use “Bash script copy rename multiple files” as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

About HuuPV

My name is Huu. I love technology, especially Devops Skill such as Docker, vagrant, git, and so forth. I like open-sources, so I created DevopsRoles.com to share the knowledge I have acquired. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.