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'
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). 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" >}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.