Reputation: 2038
I'm writing a script that will comment and un-comment field in .env file.
sed -i "s/#SENDGRID_API_KEY/SENDGRID_API_KEY/g" $mlEnv
for uncomment
sed -i "s/[^#]SENDGRID_API_KEY/#SENDGRID_API_KEY/g" $mlEnv
for comment out, I use [^#]
so that it will not add one more # when it is already commented
But second one doesnt work, although
grep "[^#]SENDGRID_API_KEY" $mlEnv
works ok.
Upvotes: 2
Views: 104
Reputation: 18641
Another try with sed
similar to potong's:
sed 's/^[[:space:]]*#*[[:space:]]*\(SENDGRID_API_KEY\)/#\1/' file > newfile
The ^[[:space:]]*#*[[:space:]]*\(SENDGRID_API_KEY\)
pattern matches any whitespace, 0+ hash chars, then again any whitespaces and then a SENDGRID_API_KEY
word captured in Group 1. The replacement is #
and then the captured value.
Upvotes: 0
Reputation: 627607
You may use
sed -i -E 's/(^|[^#])(SENDGRID_API_KEY)/\1#\2/g' "$mlEnv"
Here, -E
enables POSIX ERE regex syntax, (^|[^#])
captures (into Group 1) either start of string or any char but #
in Group 1 and (SENDGRID_API_KEY)
captures SENDGRID_API_KEY
in Group 2.
The \1#\2
replacement pattern replaces with Group 1 contents + #
+ Group 2 contents.
Variables which specify a file name argument should generally be within double quotes.
Upvotes: 2
Reputation: 58578
This might work for you (GNU sed):
sed -Ei 's/^#?(SENDGRID_API_KEY)/#\1/' file
This will replace a line beginning #SENDGRID_API_KEY
or SENDGRID_API_KEY
with #SENDGRID_API_KEY
.
Upvotes: 1