Search code examples
shellubuntunginxsedlinode

SED script how to insert line at line number if the text doesn't exist already?


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


Solution

  • 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.