简体   繁体   中英

Find a string and replace in all files inside a directory and sub-directory

I am thinking to replace a string in linux, the idea is to find all files having abc as string and replace with xyz inside a directory and all sub-directories.

Can you suggest how can I do this with Linux shell scripting

You can use find and sed, since sed will only affect files which have this string. If a file does not have the string, there's no disadvantage of running the replace anyway:

find -type f -exec sed -i 's/abc/xyzg' {} +
  • -type f only find files (exclude directories)
  • -exec for each file found execute …
  • sed -i edit files in-place
  • s/abc/xyz/g replace all occurrences of "abc" with "xyz" in all lines
  • {} + invoke the "exec" command with multiple file names at once, instead of once per file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM