Home > OS >  Find and replace a text with its match as input in shell
Find and replace a text with its match as input in shell

Time:08-26

I have a changelog file with lines that look similar to this

PROJECT-123: Added an awesome new feature
...

Now I want to edit the file to add markup style links for each reference to a ticket, like this:

[PROJECT-123](https://project.atlassian.net/browse/PROJECT-123): Added an awesome new feature
...

I found the sed command for find and replace, but how can I dynamically use the match of the regex as input in the replaced text?

CodePudding user response:

If the only variables are the project name (PROJECT-123) and the text after it (Added an awesome new feature) you can use awk with command like this:

awk -F: '{printf "[%s](https://project.atlassian.net/browse/%s):%s",$1,$1,$2}' logfile >newlogfile

CodePudding user response:

You can definitely do this with sed. You just need to capture your match.

sed 's|\(^.*\): |[\1](https://project.atlassian.net/browse/\1): |' <(echo "PROJECT-123: Added an awesome new feature")

which gives output:

[PROJECT-123](https://project.atlassian.net/browse/PROJECT-123): Added an awesome new feature

In this case \(^.*\): will capture anything from the beginning of the line through : , and that can then be referenced as \1.

  • Related