Linux Tips and Tricks

Linux Tips and Tricks

Rename the files using perl script

August7

Rename the files using perl

we can use the method rename for renaming the files using perl script.

1
2
3
4
5
6
7
8
9
10
11
$ cat rename.pl
#!/usr/bin/perl
 
use strict;
use warnings;
 
foreach $_ (@ARGV) {
my $oldfile = $_;
s/.bk//g;
rename($oldfile, $_);
}

Now i am creating some .bk files using the touch command

1
2
3
$ touch a.txt.bk
$ touch b.txt.bk
$ touch c.txt.bk

Now i have 3 .bk files in my current directory.

1
2
3
4
5
6
$ ls -lrt
total 4
-rw-rw-r-- 1 kamaraj kamaraj 126 Aug 7 23:38 rename.pl
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 a.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 b.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 c.txt.bk

execute the perl file as below.

1
$ perl rename.pl *.bk

Now you can see all the files are named ( .bk was removed )

1
2
3
4
5
6
$ ls -lrt
total 4
-rw-rw-r-- 1 kamaraj kamaraj 126 Aug 7 23:38 rename.pl
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 a.txt
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 b.txt
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 c.txt

If i want to revert back the filenames to .bk format, then you can use the below one-liner

1
2
3
4
5
6
7
8
$ ls *.txt | perl -lane '$origname=$_;s/.txt/.txt.bk/;rename($origname,$_)'
 
$ ls -lrt
total 4
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 a.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 b.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 0 Aug 7 23:38 c.txt.bk
-rw-rw-r-- 1 kamaraj kamaraj 126 Aug 7 23:42 rename.pl

Using the below for loop, we can easily rename the .txt.bk files to .txt files

1
for i in *.bk; do echo "mv ${i} ${i/.bk/}"; done
posted under Uncategorized

Email will not be published

Website example

Your Comment:


Recent Comments

    Categories