简体   繁体   中英

How to do a recursive find and replace from the command line?

Is there a simple way to recursively search all files in a directory hierarchy for a term (eg port ) and replace all occurrences of that term with another (eg port-lookup ).

I have tried the suggestions in this post , but they are only applicable for a single file.

Try this

find ./ -type f -exec sed -i -e 's/port/port-lookup/g' {} \;

If you don't want to change file modification time

grep -rl 'port' /search_in_this_dir | xargs sed -i 's/port/port-offset/g' 

The simplest (and arguably most pure and intuitive) way to achieve this is to perform a recursive file grep then pipe those file results to sed (via xargs ) to handle the in-place substitution.

grep -r -l "port" | xargs -r -d'\n' sed -i 's/port/port-lookup/g'

There is a comprehensive community wiki answer on this topic that I would recommend reading over on the Unix & Linux exchange.

If you have a recent version of bash (>4)

shopt -s globstar
sed -i 's/port/port-lookup/g' **/*

Just 1 command line: msr -rp dir1,dir2,file1,fileN -x port -o port-lookup -R

The above command recusively search and replaces plain text port to port-lookup in files.

  • If you want to preview replacing result , remove -R
  • If you want to preview and summarize files list and count/distribution, add -l
  • If you want to backup the changed files, add -K like -K -R or -RK .
  • Ignore case add -i like -i -x or -ix .
  • If you want to use C++ / C# / Java / Scala Regex syntax, use -t instead of -x .
  • Filter file name like: include -f "\\.(xml|java|cpp)$" , exclude --nf "\\.(so|a|lib|dll|obj)$"
  • Filter directory name like: include -d "src" , exclude --nd "^(target|\\.git)$"
  • Filter file size range like: --s1 1 / --s1 1B with/or --s2 1.20MB
  • Filter file last write time range like: --w1 2017-08-01 with/or --w2 "2017-08-12 11:20:30"

More usages about find and replace file or pipe just see my open project https://github.com/qualiu/msr ( msr.exe / msr.gcc* / msr.cygwin are in the tools directory). Built-in usage and exmaples just run the exe. Docs like performance comparision with findstr and grep .

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