简体   繁体   中英

Batch Renaming of Files in Linux

I have about 1000 files that i need renamed. The current format is:

exten-B12345678910-C45679891254-D12345645-E4578981-G6546525.1.wav

I would like to remove exten- & -G6546525.1 . The "exten-" part of the file name is the same in all files but the -G6546525.1 part is different in all files. Is there a script to remove both parts and just leave B12345678910-C45679891254-D12345645-E4578981.wav as the file name?

Hope I have made myself clear.

for f in "exten-*-G*.wav" ; do
    mv "$f" "$(echo $f | sed 's/exten-\(.*\)-[^-]*\.wav/\1.wav/')"
done

This is designed to work on the designated file formats and might fail in cases of globbing characters, etc.

Here's how to get the parts of the file name you want using bash or ksh:

$ x="exten-B12345678910-C45679891254-D12345645-E4578981-G6546525.1.wav"
$ echo "$x"
exten-B12345678910-C45679891254-D12345645-E4578981-G6546525.1.wav

$ y="${x#*-}"
$ echo "$y"
B12345678910-C45679891254-D12345645-E4578981-G6546525.1.wav

$ z="${y%-*}"
$ echo "$z"
B12345678910-C45679891254-D12345645-E4578981

To clarify how to use the above to rename files:

for x in *
do
    y="${x#*-}"
    mv -- "$x" "${y%-*}.wav"
done

Note that other shells may have briefer methods, eg zsh has some powerful constructs and some shells have a rename command.

I do this kind of batch work using PHP and phpSecLib2 running on my linux box.

Using SecLib, run an SSH connection into the Linux box you want to rename the files on, and run an "ls" inside the folder. Then explode the list of files into a PHP array, followed by a for each loop.

Example code as follows (assuming file location on server is in /home/user/files/ and server location is localhost):

    <?php

include('Net/SSH2.php');

$ssh = new Net_SSH2('localhost');
if (!$ssh->login('SSHUSER', 'SSHPASS')) {
                exit('Login Failed');
}

$filelist = $ssh->exec("cd /home/user/files;ls");

$filearray = explode("\n", $filelist);

foreach ($filearray as $key) {

    $newarray = explode("-", $key);
    $newfile = $newarray[1] . $newarray[2] . $newarray[3] . $newarray[4] . ".wav";
    $newfile = (string)$newfile;
    $oldfile = (string)$key;

    $rename = "cd /home/user/files;mv '" . $oldfile . "' '" . $newfile . "'";
    $rename = (string)$rename;
    $runrename = $ssh->exec($rename);
}
echo "Done!";
?>

The above code should work with minimal changes (username/password and folder location changes).

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