One day, I want to edit all files within a directory and it will be a nightmare if you open it one by one and search replace them one by one. DO NOT do that, it is completely stupid, Linux has tons of tools to do it easily for you just in one command and type “ENTER” and everything is done for you.
You can do using find or perl. I like find and xargs the best, because it can more flexible on the files you want to edit search and replace, example you can do -size for size or -atime for last accessed time or -iname for case insensitive or -perm for permission files, and more…
Do ‘man find’ for more information and also don’t forget ‘man xargs’
1. Using find command
Example:
Search for HTML comment, starting with “<!– Tjenarvi Comment” and ending with “–>” which is the ending of HTML comment and replace it with nothing/blank (not the word “nothing/blank”, but really nothing and blank)
Syntax of sed for search and replace command:
sed -i ’s/SEARCH/REPLACE/g’
Syntax of xargs:
xargs <the command>
-i means edit in-place
s/ means search
/g means regular expressions global within a file
The Final Command:
# find . -iname ‘*.html’ -type f | xargs sed -i ’s/<!– Tjenarvi Comment.*–>//g’
Question: Why not using -exec of a ‘find’ command? Example: find . -iname ‘*.html’ -type f -exec sed -i ’s/<!– Tjenarvi Comment.*–>//g’ {} \;
Answer: Using xargs is faster rather than “-exec” option in find command. You want to prove? I will discuss it later in next post, I promise
2. Using perl command
Example:
You want to change all the href stylesheet in all *.php files
From
<link rel=”stylesheet” type=”text/css” href=”../includes/style.css”>
To
<link rel=”stylesheet” type=”text/css” href=”style.css”>
Syntax of perl command:
perl -pi -w -e ’s/search/replace/g;’ *.php
-p loop
-i means edit in-place
-w write warnings
-e means execute the following line of code.
As each expression is a regular expression you’ve got to escape the special characters such as forward slash like / and . which is a dot:
\.\.\/includes\/style\.css
So, the Final Command:
# perl -pi -w -e ’s/\.\.\/includes\/style\.css/style\.css/g;’ *.php
Hope this helps a lot of people
Copyright © 2006-2009 Tjenarvi, Inc. All rights Reserved.
Comments »
Offers
Earn Money
Shout Me
Google Friends
Traffic Helps
Statistics





Twitter
Facebook





No comments yet.