[英]Issue with sed search and replace with brackets
I am replacing the below file (sample.txt):我正在替换以下文件 (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: 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:但是,当我尝试将
](./img
替换为" src="/images/post
时,出现错误。我在下面尝试过,但它没有改变任何东西:
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您可以使用基于 POSIX BRE 的解决方案,例如
sed -i 's~!\[\([^][]*\)](\./img/\([^()]*\))~{{< image alt="\1" src="/images/post/\2" >}}~g' file
Or, with POSIX ERE:或者,使用 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 !\[
- 一个![
substring\([^][]*\)
- Group 1 ( \1
, POSIX BRE, in POSIX ERE, the capturing parentheses must be escaped): zero or more chars other than [
and ]
\([^][]*\)
- 第 1 组( \1
,POSIX BRE,在 POSIX ERE 中,必须转义捕获括号): [
和]
以外的零个或多个字符](\./img/
- ](./img/
substring (in POSIX ERE, (
must be escaped) ](\./img/
- ](./img/
substring(在 POSIX ERE 中, (
必须转义)\([^()]*\)
- Group 2 ( \2
): any zero or more chars other than (
and )
\([^()]*\)
- 第 2 组 ( \2
):除(
和)
之外的任何零个或多个字符)
- a )
char (in POSIX BRE) (in POSIX ERE it must be escaped). )
- a )
char(在 POSIX BRE 中)(在 POSIX ERE 中它必须被转义)。Suggesting single awk
command to do all the transformations.建议使用单个
awk
命令进行所有转换。
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" >}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.