使用sed进行多行替换

问题描述 投票:0回答:1

由于实用程序中的错误,我需要找到一系列行并更改它们。我一直在尝试使用sed,但无法弄清楚macOS上的语法。

基本上,我需要找到以下几行:

type: DataTypes.DATE,
allowNull: true,
primaryKey: true

...如果此序列存在,则更改最后两行:

type: DataTypes.DATE,
allowNull: true

整个文件最初看起来像这样:

/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('product', {
    id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      primaryKey: true
    },
    _u: {
      type: DataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'user',
        key: 'id'
      }
    },
    _v: {
      type: DataTypes.DATE,
      allowNull: false
    },
    _d: {
      type: DataTypes.DATE,
      allowNull: true,
      primaryKey: true
    }
  }, {
    tableName: 'product'
  });
};
bash sed makefile sequelize.js
1个回答
2
投票

对于sed中的多行模式匹配,您将需要使用N命令将下一行拉入模式空间。如果我理解你的要求,这样的事情应该是诀窍:

$ cat multiline-replace.sed 
/type: DataTypes.DATE,/{N
    /allowNull: true/{N  
       /primaryKey: true/{
         s/allowNull: true/why would I allow this?/
         s/primaryKey: true/shmimaryKey: false/
       }      
    }
}

这个想法是,当/type: DataTypes.DATE,/匹配时,你读到模式空间的下一行(范围由{}分隔。在你的allowNull: true线和你的primaryKey: true线上做同样的事情。然后你在模式空间中有三条线你可以做他们想做的修改.s/pattern/replacement/

我将你的输入复制到文件input然后我测试它对这个程序:

$ cat input | sed -f multiline-replace.sed 
/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('product', {
    id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      primaryKey: true
    },
    _u: {
      type: DataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'user',
        key: 'id'
      }
    },
    _v: {
      type: DataTypes.DATE,
      allowNull: false
    },
    _d: {
      type: DataTypes.DATE,
      why would I allow this?,
      shmimaryKey: false
    }
  }, {
    tableName: 'product'
  });
};
$

另请参阅Unix堆栈交换上的这篇文章,其中提供了有关sed命令的更多详细信息(man sed也是您的朋友):https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string#26290

© www.soinside.com 2019 - 2024. All rights reserved.