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
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

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,842
  • 1
  • 18
  • 32
Lars Fischer
  • 9,135
  • 3
  • 26
  • 35