0

In various files in lots of sub folders I have the following text in large text files, each unique

Linux.Secret = 'XYZZYXZYXZYXZYXZYXZ'

I would like to make it so all the Linux.Secret = '' are the same as Linux.Secret = 'NEWSECRET'

How can I do this?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
masterq
  • 171

1 Answers1

2

First find all files that contains Linux.Secret = at the start of a line:

find . -type f -exec grep -q '^Linux.Secret =' {} ';'

Note that grep -q does not output anything, it just exits with a status depending on whether the expression could be matched or not.

Then, for all files that passes these tests (is a regular file and contains that text), we run a simple (GNU) sed command:

find . -type f -exec grep -q '^Linux.Secret =' {} ';' \
    -exec sed -i "s/^Linux.Secret =.*/Linux.Secret = 'NewSecret'/" {} +

This makes the change in-place in the files by substituting the whole line with the line we'd like to have. We handle the single quotes by using double quotes around the expressions that require it.

If you need to be more careful with the matching and only match Linux.Secrets = followed by something in single quotes:

find . -type f -exec grep -E -q "^Linux.Secret = '[^']+'" {} ';' \
    -exec sed -E -i "s/^Linux.Secret = '[^']+'.*/Linux.Secret = 'NEWSECRET'/" {} +

Related:

Kusalananda
  • 333,661