Fred Lackey
Fred Lackey

Reputation: 2391

How to replace multiple lines in a file (or multiple files)?

One of my favorite utilities, sequelize, will automatically generate models from a database. However, it does not always recognize auto-increment functions on primary keys. This causes the model to sometimes generate wrong and causes errors when inserting. How can I search for the lines for the primary key and replace those lines with the correct lines (having the autoIncrement flag)?

For example, this ...

    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      primaryKey: true
    },

... needs to become, this ...

    id: {
      type: DataTypes.INTEGER.UNSIGNED, 
      autoIncrement: true, 
      primaryKey: true 
    },

I've tried using sed in the past but run into problems with the spacing, multi-line syntax, and remembering the command structure.

Upvotes: 0

Views: 415

Answers (1)

Fred Lackey
Fred Lackey

Reputation: 2391

I created a utility, called file-line-replacer, to solve this issue. It was written for Node, so, as long as you have Node installed on your Mac / Linux / Windows machine, you will be able to use it without issue.

First, install it (I prefer installing it globally)...

npm i -g file-line-replacer

... then, simply run one command (this example was for for the sequelize issue above) ...

file-line-replacer \
  --search-dir "/Users/flackey/my-project/src/data/models" \
  --backup-dir "/Users/flackey/my-project/_backup" \
  --old-lines "allowNull: false,|primaryKey: true" \
  --new-lines "autoIncrement: true,|primaryKey: true" \
  --overwrite

The above command will match entire BLOCKS of lines. So, in this example, the primaryKey: true line ensures it will target the correct area. It will then replace the block of text in --old-lines with the block of text in --new-lines And, because the --backup-dir is supplied, it will create a backup of each file before modifying the original.

Note: The default delimiter for lines is | (pipe), however you can select your own delimiter by passing in --delimiter, to set globally, or --old-lines-delimiter / --new-lines-delimiter to set it for that specific block of lines (in case you need to actually search for or replace lines having the default delimiter).

There are tons of other options listed on the project page: https://github.com/FredLackey/file-line-replacer

Upvotes: 0

Related Questions