'Issue with sed search and replace with brackets
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 1:[1]
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).
Solution 2:[2]
Suggesting single awk command to do all the transformations.
awk -F"[\\\]\\\[\\\(\\\)]" '{sub("./img","/images/post");printf("{{< image alt=\"%s\" src=\"%s\" >}}", $2, $4)}' <<< $(echo '')
Results:
{{< image alt="top command output linux" src="/images/post/wp-content-uploads-2022-04-top-command-output-linux.jpg" >}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
| Solution 2 | Dudi Boy |
