Wednesday, January 7, 2015

[Linux] How to change text in files with grep & perl command

  If you want to change some text in files, normally you use text editor. Is it right?
  But, If you use linux or unix like that, you can use grep & perl. When use that you are getting powerful. It's very comvenient and easy!



  First, I want to replace some text in .sql file. Because of that, I made .sql file with mysqldump command.

  Command : mysqldump -u[username] -p [databasename] > [destination file name]
 
  After that, you can see 'Enter password:' line. Then type your passwords. Now you got .sql file.

  Next step is changing text in .sql file with grep command

  1. Finding string in sub directories.
  Command : find . -name '*.*' | xargs grep "[string what you want find]"

  2. Finding string in sub directories and replace that with certain string
  Command : find . -name '*.*' -exec perl -pi -e 's/[string what you want to find]/[certain string what you replace with it]/g' {} \;

  If I run command "find . -name '*.*' -exec perl -pi -e 's/iloveyahoo/ilovegoogle/g' {} \;". Then I will get file there is ilovegoogle only not iloveyahoo.

  3. Finding string in a file and replace that with certain string
  Command : find . -name '[file name what you want to find in]' -exec perl -pi -e 's/[string what you want to find]/[certain string what you replace with it]/g' {} \;

  Yeah! It's so easy. Right?

No comments:

Post a Comment