Search code examples
bashsedredhat

sed: test for $pattern in $line before adding it


Several examples exist of how to use sed to add text to the end of a line based on matching a general pattern. Here's one example.

In that example, the poster starts with

somestuff...
all: thing otherthing
some other stuff

and wants to add to the end of all:, like this:

somestuff...
all: thing otherthing anotherthing
some other stuff

All well and good. But, what happens if anotherthing is already there?!

I'd like to find the line starting with all:, test for the existence of anotherthing, and only add it if it is missing from the line.

How might I do that?

My specific case is testing kernel lines in grub.conf for the existence of boot= and fips=1, and adding either or both of those arguments only if they're not already in the line. (I want the search/add to be idempotent.)


Solution

  • This might work for you (GNU sed):

    sed '/^all:/!b;/anotherthing/!s/$/ anotherthing/' file
    

    Disrequard any lines not starting with all: and only substitute lines that do not contain anotherthing.