1

I am trying to do a mass search and replace across many files where I replace a keyword in the file, lets say myKeyword, with the name of the current file.

So in file1.php the phrase myKeyword would become file1; in file2.php it would become file2; and so on until all the files are completed.

I was wondering if this is possible using scripts or a text editor function.

mlapaglia
  • 852
  • 14
  • 31

1 Answers1

1

With GNU sed:

$ for filename in $(find . -type f -name "*"); do sed -i "s/myKeyword/$(basename ${filename} | cut -f 1 -d '.')/g" "${filename}"; done
  • basename: strip full path from filename - path/to/file1.txt -> file1.txt
  • cut -f 1 -d '.': strip file extension - file1.txt -> file1

On OSX (BSD sed instead of GNU) you'll need to write sed -i '' "s/myKeyword/... instead (empty string '' after -i). See this answer for the difference: https://unix.stackexchange.com/a/272041/374001

evnp
  • 191
  • 1
  • 6