codebeaver
codebeaver

Reputation: 11

Append/replace string to a line using sed

I am trying to parse a file test.txt and append "https://" to the following string within the file:

 "1234.def.efj.abcd-1.nopqrs.com"

Note: the string has white space and the quotes at the beginning and end. Also def, efj, and nopqrs.com are static and won't change.

I am trying to accomplish this via sed. So far I have:

sed -e 's#^\s*[\"][0-9]+[\.]def[\.]efj[\.][a-z]+[\-][a-z]+[\-][0-9][\.]nopqrs[\.]com$#\s+[\"]https[\:][\/][\/][0-9]+[\.]def[\.]efj[\.][a-z]+[\-][a-z]+[\-][0-9][\.]nopqrs[\.]com#g' test.txt

When I run that command I just get the file output without the change. I have gone through other sed posts and can't seem to figure out what is wrong with my expression. Thanks in advance for your help!

Upvotes: 1

Views: 323

Answers (1)

Aserre
Aserre

Reputation: 5062

Something like this should work :

sed -i 's#"\([^"]*\.nopqrs\.com\)"#"https://\1"#g' file.txt

Explanation :

  • sed -i : inplace editing. sed will update file.txt accordingly. Note that the behaviour and syntax is implementation specific.
  • "\([^"]*\.nopqrs\.com\)" :
    • [^"]*\.nopqrs\.com: we look for any number of characters that are not quotes, followed by .nopqrs.com
    • \( ... \) : syntax for sed to create a capture group with the content matched by the expression between the parenthesis
  • \1 : we display the content of the first capture group

Upvotes: 1

Related Questions