>Linux – Rename files

>How to rename recursively files in all the filesystem

The simplest method that I have found to rename recursively a group of file is to use the “rename” linux bash command with a simple perl regular expression.
To rename all the file with extension containing the word “foo” I can use the following command:


$ rename s/foo/dog/ *foo*

To rename all the files with “.txt” extension you only need to specify *.txt instead of *foo*, as shown in the following example:

$ rename s/foo/dog/ *.txt 

The real problem occurs when you want to change recursively the file name into multiple directory and sub directory.
I usually  use this simple bash script to accomplish this task:

$ for dir in $(find /root/truepoint -type d); do cd $dir; rename s/foo/doog/ *.txt; done
Notice as you cannot use simply the command:

$ for var in $(find /root/truepoint -type d); do rename s/foo/doog/ $var; done
because:
  1. “rename” command rename all file matching a rule (2th argument) into the current directory
  2. “rename” 2th argument is the file typology and not a directory 

so you need to a command to change recursively the current directory.

Enjoy your Linux!


>Perl hacks

>How to replace recursively a word into a file

One of  the most frequent task of a linux engineer is to manipulate words within files. Many times this task can be accomplished with linux basic tools like sed, awk, grep using obviously pipe (‘|’) to correlate them.
But suppose that you would like to replace recursively one, all or some occurrences of a word into a file without modify the rest of file but only replacing the chosen word(s) and also you want to do this task at command line without use a dedicated script?

The answer is: “You can use Perl!”

Suppose you want replace all the occurrences of the word ‘foo’ with the word ‘dog’ within the file ‘foo.txt’ . You can write at command line:

$ perl -p -i -e “s/foo/dog/g” foo.txt

-p: is like the cycle while(<>){….} to read a file line to line.
-i: without this option the command redirect his output to terminal. With this options the stdout  is redirected to our file.
-e: is the option to specify a command

Simple, not?

Obviously if you want to replace only the first occurrence of ‘foo’ you need to delete ‘\g’ from the ‘s///’ operator.

The problem is: “ok, I’m able to replace one or all the occurrences of a word, but I would like to replace only some of them, when a particular condition is verified”.
The answer is: “don’t worry friend, you need only to use the ‘m//’ operator and a simple if condition within the perl command. Suppose the the condition is the presence of word ‘animal’. The command will be:

$ perl -p -i -e “s/foo/dog/g if m/ if m/animal/” foo.txt

To use this command to replace one, some or all the occurrences of a word in many files you can use simply this cycle:


for file in $(find /…); do $ perl -p -i -e “s/foo/dog/g if m/ if m/animal/” $file; done


Enjoy this command!