2

I have a sed script that does insert a text line at a certain line.

Here's my sed script:

  • 20i - the line number
  • \ - inserts into a new line line number has something in it.
  • import NewPage from './newpage/index'; - the text line inserted into the line.

file - the file where the text is.

sed -i "20i \ import NewPage from './newpage/index'; " file

What I'm trying to achieve is: the ability to check if the keyword "NewPage" exists in the document -> than do not insert the sed line.

Any way to do this?

Thanks in advance, AT

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

1 Answers1

1

You could use a combination of grep and your command and || in bash like this:

grep -c NewPage yourfile || sed -i "20i \ import NewPage from './newpage/index'; " yourfile

It works like this:

  • if the first command is not successful (finding the word), then second command after the || is executed
  • if the first command is successful, then the second is skipped.
DavidC
  • 1,782
  • 1
  • 18
  • 30
Lars Fischer
  • 8,410
  • 3
  • 27
  • 33