user3076396
user3076396

Reputation: 11

Search and Replace Keyword with File Name across Multiple Files

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.

Upvotes: 1

Views: 37

Answers (1)

evnp
evnp

Reputation: 301

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

Upvotes: 1

Related Questions