Monday, August 21, 2006

Linux : find and replace with grep and sed

Following command finds PATTERN and replaces it with REPLACEMENT in all files under directory/path/.

grep -rl PATTERN directory/path/ | xargs sed -i 's/PATTERN/REPLACEMENT/g'

Notes :

-r option of grep does recursive search
-i option of sed edits files in place
g does substitutions in all occurences

Wednesday, August 16, 2006

Bash : Saving time with Environment Variables

You can create an environment variable $dr (for document_root) to save typing the whole path /var/www/html.

In your .bashrc file add this line

export dr=/var/www/html

Then source .bashrc. After this you'll be able to use shortcuts like

vi $dr/index.htm

With export, we create a new environment variable. In c shell, the syntax is

setenv dr /var/www/html

You can see all the environment variables with env.

Thursday, August 10, 2006

Perl : Regular Expression to match an email address

Following regular expression matches a valid email address

/^(\w|\-|\_|\.)+\@((\w|\-|\_)+\.)+[a-zA-Z]{2,}$/

To learn more about regular expressions in Perl, read

man perlre

Linux : find files, find patterns and replace in one go

Following command finds all text file in current working directory and replaces XYZ with ABC in all found files.

find . -name "*.txt" -exec perl -pe 's/XYZ/ABC/g' -i {} \;

Notes
  • You need to have perl installed on your system
  • with -exec you can execute a command on the found files
  • -i option of perl is used to update files
  • -p option of perl command assumes a loop around the code just like the -n switch. Only difference is that it prints the lines.
  • XYZ is a regular expression to be searched and ABC is the replacement text.

Tuesday, August 01, 2006

Fwd: Back after many days !

Hi !

I am back after many days of inactivity.