簡體   English   中英

問題 sed 搜索並用括號替換

[英]Issue with sed search and replace with brackets

我正在替換以下文件 (sample.txt):

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

和:

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

另外,我需要進行內聯文件替換。 這是我所做的:

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)

但是,當我嘗試將](./img替換為" src="/images/post時,出現錯誤。我在下面嘗試過,但它沒有改變任何東西:

sed -i -e 's/^!\[/\{\{< image alt="/g' -e 's/\]\\(.\/img/\" src=\"\/images\/post/g' sample.txt

所以基本上問題出在第二次替換上:

's/\]\\(.\/img/\" src=\"\/images\/post/g'

您可以使用基於 POSIX BRE 的解決方案,例如

sed -i 's~!\[\([^][]*\)](\./img/\([^()]*\))~{{< image alt="\1" src="/images/post/\2" >}}~g' file

或者,使用 POSIX ERE:

sed -i -E 's~!\[([^][]*)]\(\./img/([^()]*)\)~{{< image alt="\1" src="/images/post/\2" >}}~g' file

請參閱在線演示 正則表達式的工作方式如下所示

詳情

  • !\[ - 一個![ substring
  • \([^][]*\) - 第 1 組( \1 ,POSIX BRE,在 POSIX ERE 中,必須轉義捕獲括號): []以外的零個或多個字符
  • ](\./img/ - ](./img/ substring(在 POSIX ERE 中, (必須轉義)
  • \([^()]*\) - 第 2 組 ( \2 ):除()之外的任何零個或多個字符
  • ) - a ) char(在 POSIX BRE 中)(在 POSIX ERE 中它必須被轉義)。

建議使用單個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)')

結果:

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM