Shree Iyer
Shree Iyer

Reputation: 69

Replace string containing _ and double quotes inside a file

Might be a repeat question, but I am kind of stuck: I have a file test.txt with the following contents:

# To push each commit to a remote, put the name of the remote here.
# (eg, "origin" for git). Space-separated lists of multiple remotes
# also work (eg, "origin gitlab github" for git).
PUSH_REMOTE=""

I simply want to replace the line in the file that contains PUSH_REMOTE="" with PUSH_REMOTE="origin". Was looking for a sed or awk syntax to achieve the same. I tried escaping the double quotes using sed -i 's#PUSH_REMOTE=""#"PUSH_REMOTE="origin"#g' test.txt, But I keep getting the error sed: 1: "test.txt": undefined label 'est.txt'.

The desired output (file contents of test.txt) is as follows:

# To push each commit to a remote, put the name of the remote here.
# (eg, "origin" for git). Space-separated lists of multiple remotes
# also work (eg, "origin gitlab github" for git).
PUSH_REMOTE="origin"

Thanks again in advance for your time to address this somewhat basic issue of mine!

Here are my os-release details, in case it helps:

NAME="Red Hat Enterprise Linux"
VERSION="8.3 (Ootpa)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="8.3"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Red Hat Enterprise Linux 8.3 (Ootpa)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:8.3:GA"
HOME_URL="https://www.redhat.com/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8"
REDHAT_BUGZILLA_PRODUCT_VERSION=8.3
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8.3"

Upvotes: 1

Views: 275

Answers (2)

Ed Morton
Ed Morton

Reputation: 204638

The error message sed: 1: "test.txt": undefined label 'est.txt' probably means you're using a sed that doesn't have a -i option or, more likely, whose -i option requires a temp file name after it and so it's treating your script as that temp file name and then treating your file name as the script. Either that or you just have a plain old syntax error in your sed script.

This will do what you want using any sed in any shell on every Unix box:

$ sed 's/\(PUSH_REMOTE=\)""/\1"origin"/' file
# To push each commit to a remote, put the name of the remote here.
# (eg, "origin" for git). Space-separated lists of multiple remotes
# also work (eg, "origin gitlab github" for git).
PUSH_REMOTE="origin"

Do whatever you like to update the input file with that output, e.g. either of these:

  • sed -i '...' file, or
  • sed -i '' '...' file, or
  • sed '...' file > tmp && mv tmp file

or whatever.

Upvotes: 1

F. Knorr
F. Knorr

Reputation: 3065

Could you check whether this awk-command works:

awk '$0~/^PUSH_REMOTE=""$/{$0="PUSH_REMOTE=\"origin\""}1' test.txt

Upvotes: 0

Related Questions