Home > OS >  Issue with sed search and replace with brackets
Issue with sed search and replace with brackets

Time:05-03

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

![top command output linux](./img/wp-content-uploads-2022-04-top-command-output-linux.jpg)

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'

CodePudding user response:

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).

CodePudding user response:

Suggesting single awk command to do all the transformations.

 awk -F"[\\\]\\\[\\\(\\\)]" '{sub("./img","/images/post");printf("{{< image alt=\"%s\" src=\"%s\" >}}", $2, $4)}' <<< $(echo '![top command output linux](./img/wp-content-uploads-2022-04-top-command-output-linux.jpg)')

Results:

{{< image alt="top command output linux" src="/images/post/wp-content-uploads-2022-04-top-command-output-linux.jpg" >}}
  • Related