1

Im trying to use sed to add a line after a specific string in a file. Can anyone help?

File name:

example.js

Existing line:

localeData: require('react-intl/locale-data/en'),

Desired output:

localeData: require('react-intl/locale-data/en'),
messages: require('../locale/messages_en'),

UPDATE: Some progress, this command replaces the string being searched with the string I want appended.I don't want it replaced:

sed 's/react-intl\/locale-data\/en/..\/locale\/messages_en/g' example.js
anubhava
  • 761,203
  • 64
  • 569
  • 643
Jay.F
  • 101
  • 9
  • 1
    updated @anubhava no not limited to using sed, any command that required no manual intervention (this is part of a script). Sed is just the overwhelming majority of results when searching 'how to add a line after a specific string in a file' – Jay.F Sep 10 '20 at 17:29
  • Does this answer your question? [Insert line after first match using sed](https://stackoverflow.com/questions/15559359/insert-line-after-first-match-using-sed) – thanasisp Sep 10 '20 at 18:50

2 Answers2

2

You may use this non-regex way using awk:

awk -v s="localeData: require('react-intl/locale-data/en')," \
    -v r="messages: require('../locale/messages_en')," '
1
index($0, s) {
   print r
}' file
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Use a operator to insert a line after a matched line in sed:

sed '/react-intl\/locale-data\/en/a messages:   require('..\/locale\/messages_en'),' example.js

react-intl\/locale-data\/en matches a line with react-intl/locale-data/en string in it, and a messages: require('..\/locale\/messages_en'), inserts messages: require('../locale/messages_en'), right below.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37