2

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

Community
  • 1
  • 1
dafydd
  • 267
  • 1
  • 2
  • 10

3 Answers3

2

Skip lines with anotherthing and add it to the remaining lines starting with all:

sed '/anotherthing/!s/^all:.*$/& anotherthing/' file
Walter A
  • 19,067
  • 2
  • 23
  • 43
1

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.

potong
  • 55,640
  • 6
  • 51
  • 83
1

You can use this awk to check for existence of the given string and append it only if it is not there:

awk -v s='anotherthing' '/^all:/ && $0 !~ s "$" { $0 = $0 OFS s } 1' file
anubhava
  • 761,203
  • 64
  • 569
  • 643