DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Search or Replace String Recursively in a Directory on Linux


Find String Using grep

in zsh

grep target_pattern */.erl

in bash

grep -r --include="*.java" Forward .

Format: grep [-r] [--include="..."] searched_target_pattern search_base_dir, in which -r means search recursively (including subfolders), --include specify file types;

Replace String Using Perl

perl -i -pe 's/oldstring/newstring/g' <file_pattern>. For example, if you want replace all "windows" with "linux" in directory "~/docs" in all xml files, and save old files as "*.bak", yuo shoud run the following command in docs:

perl -i.bak -pe 's/windows/linux/g' *.xml

Note: there is no blank between "-i" and ".bak";

Replace all files including subdirs:

perl -i.bak -pe 's/windows/linux/g' **/*.xml

No backup file needed:

perl -i -pe 's/windows/linux/g' **/*.xml

Do not modify file, output to console:

perl -pe 's/windows/linux/g' aa.xml

Ref: http://vasir.net/blog/ubuntu/replace_string_in_multiple_files/



Published

Jun 26, 2013

Last Updated

Jun 26, 2013

Category

Tech

Tags

  • grep 3
  • linux 158
  • perl 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor