Home > Enterprise >  Add one line of code after a specific matched line
Add one line of code after a specific matched line

Time:02-20

I have a file like this:

some
code
const parameterParens = new WeakSet();
some
other 
code

I want to turn it into:

some
code
const parameterParens = new WeakSet();
module.exports.create.offsets = offsets;
some
other 
code

What I am doing at the moment is intolerable:

sed -i -- 's/const parameterParens = new WeakSet();/const parameterParens = new WeakSet();\nmodule.exports.create.offsets = offsets;\n/g' file.js

I would like to at least not have to repeat the match line:

sed -i -- 's/(const parameterParens = new WeakSet\(\);)/$1\nmodule.exports.create.offsets = offsets;\n/g' file.js

Which doesn't work. I am not set on using sed, but I would like to keep it as basic as possible (no perl, etc).

CodePudding user response:

If you use awk instead of sed then you don't have to worry about regexp or backreference metachars like you would with sed (see is-it-possible-to-escape-regex-metacharacters-reliably-with-sed) since awk has literal string operations:

$ awk '{print} $0=="const parameterParens = new WeakSet();"{ print "module.exports.create.offsets = offsets;" }' file
some
code
const parameterParens = new WeakSet();
module.exports.create.offsets = offsets;
some
other
code

CodePudding user response:

Using sed

$ sed 's/new WeakSet();/&\nmodule.exports.create.offsets = offsets;/' input_file
some
code
const parameterParens = new WeakSet();
module.exports.create.offsets = offsets;
some
other
code
  • Related