1

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Be sure to check which implementation of sed you are using; they differ as to whether -i (if supported at all) requires an argument or not.
That's a bit over-quoted. You don't need to escape the double quotes (") because the appear inside single quotes (which protects them from interpretation by the shell) and they are not special to sed. It still works; it's just harder to read than it needs to be.
I don't understand why people are so eager to use -i in their answers - chances are the OP doesn't know what it does and when they go to test your answer they accidentally wreck their input file! Let the OP add -i on their own later if they want it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.