Batch Renaming Files in Linux(批量重命名linux)

Linux provides an easy way of renaming multiple files at once. Here’s how to do it using a bash for loop.

Batch renaming files within the Linux operating system is very easy. Many times it’s necessary to change a large list of file names from one form to another, and the Linux command line provides a great way of doing this. Let’s take a look at a specific example.

Say we had a bunch of .txt files with long names, like:

`longfilename1.txt

longfilename2.txt

longfilename3.txt

longfilename4.txt`

We want to make all the file names short and consistent with a prefix of ‘short’ and a number. It would look like this:

`short1.txt

short2.txt

short3.txt

short4.txt`

To do this, we’ll use a bash for loop and a short bit of code. The code looks like this:

`#!/bin/bash

for x in *.txt; do

mv “$x” “short${x%.txt}”;

done`

This code will go through all the files in the current directory and change the prefix to ‘short’ and add a numerical value, starting from 1. All the .txt files in the current folder will get their names changed in the same manner.

To use this code, open up a terminal window and type:

`$ chmod +x renamer.sh`

The chmod command will make the renamer.sh bash script executable. After that, you can run the script with the command:

`$ ./renamer.sh`

And that’s all there is to it. You’ve just renamed multiple files fast and easy.

Batch renaming isn’t the only file-handling task the Linux command line can do. There are many other helpful options. Whether you need to delete multiple files, move and copy a lot of them around, compress them into an archive, or just want an extra layer of control, the Linux command line is the perfect tool.

With just a few commands, you can make some amazing changes to your file structure. Give it a try and take a look at what you can accomplish!


数据运维技术 » Batch Renaming Files in Linux(批量重命名linux)