adamreisnz / replace-in-file

A simple utility to quickly replace contents in one or more files
580 stars 65 forks source link

Feature Request: Use filename in `to` field #121

Closed mesqueeb closed 4 years ago

mesqueeb commented 4 years ago

I'd love to be able to insert the filename when replacing something.

Eg. the example below would

  1. take a regex that matches the entire file contents
  2. replace it with the same content, but add an extra line with the filename
const options = {
  from: /([\S\s]+)/,
  to: (file) => `${file.name}\n$1`,
}
adamreisnz commented 4 years ago

This is already possible: https://github.com/adamreisnz/replace-in-file#using-callbacks-for-to

This callback provides for an extra argument above the String replace method, which is the name of the file in which the replacement is being performed.

const options = {
  files: 'path/to/file',
  from: /SomePattern[A-Za-z-]+/g,
  to: (...args) => args.pop(), //The last argument is the filename
};