0

What would be the best way of going about this.

If a line starts with a string, replace that whole line with new string If no line in the file starts with that string, append it to the file

Ex:

file.txt:

FOO=blah
BAR=bleh
GIN=blop

How can I replace the FOO line if it exists or append to the file if no line starts with FOO?

cclloyd
  • 8,171
  • 16
  • 57
  • 104

1 Answers1

0

You can try this command,

if grep -q -F 'FOO' file.txt ; then sed -i 's/FOO/newline/g' file.txt; else echo newline >> file.txt; fi

or (depending or your version of sed)

if grep -q -F 'FOO' file.txt ; then sed -i '' 's/FOO/newline/g' file.txt; else echo newline >> file.txt; fi
myradio
  • 1,703
  • 1
  • 15
  • 25