Issue
I am replacing the below file (sample.txt):

with:
{{< image alt="top command output linux" src="/images/post/wp-content-uploads-2022-04-top-command-output-linux.jpg" >}}
Also, I need to do an inline file replacement. Here is what I have done:
sed -i -e 's/^!\[/\{\{< image alt="/g' sample.txt
Output:
{{< image alt="top command output linux](./img/wp-content-uploads-2022-04-top-command-output-linux.jpg)
But when I try to replace ](./img
with " src="/images/post
, I am getting errors. I have tried below, but it does not change anything:
sed -i -e 's/^!\[/\{\{< image alt="/g' -e 's/\]\\(.\/img/\" src=\"\/images\/post/g' sample.txt
So basically the problem is with the 2nd substitution:
's/\]\\(.\/img/\" src=\"\/images\/post/g'
Solution
You can use a POSIX BRE based solution like
sed -i 's~!\[\([^][]*\)](\./img/\([^()]*\))~{{< image alt="\1" src="/images/post/\2" >}}~g' file
Or, with POSIX ERE:
sed -i -E 's~!\[([^][]*)]\(\./img/([^()]*)\)~{{< image alt="\1" src="/images/post/\2" >}}~g' file
See the online demo. The regex works like is shown here.
Details:
!\[
- a![
substring\([^][]*\)
- Group 1 (\1
, POSIX BRE, in POSIX ERE, the capturing parentheses must be escaped): zero or more chars other than[
and]
](\./img/
-](./img/
substring (in POSIX ERE,(
must be escaped)\([^()]*\)
- Group 2 (\2
): any zero or more chars other than(
and)
)
- a)
char (in POSIX BRE) (in POSIX ERE it must be escaped).
Answered By - Wiktor Stribiżew Answer Checked By - Katrina (WPSolving Volunteer)