将特殊的内联代码样式更改为 Markdown 中的块代码样式

Change special inline code styling to block code styling in Markdown

我在用 Markdown 编写的教程中使用独特的风格来演示代码。

使用 GitHub 代码块中的新“复制”按钮(截至 21 年 5 月),我想更改所有内联命令以阻止 console 代码,从而制作我的教程对学生来说更容易。

(如有需要,欢迎查看实战教程:VIP Linux

我的问题

其中 34 可以是任何数字、字母或连字符

评论可能存在也可能不存在

所有文件都以 .md

结尾

我想改变这个:

| **34** :$ `one cli command here` Optional `code` comment, *maybe* with <kbd>Ctrl</kbd> + <kbd>Z</kbd>

...为此:

| **34** :$ Optional `code` comment, *maybe* with <kbd>Ctrl</kbd> + <kbd>Z</kbd>

```console
one cli command here
```

我的研究

我可以轻松地使用 sed 进行部分操作

sed 's/** :$ `/** :$\n```console\n/' *.md | sed 's:` :\n```\n\n:'

变化中:

| **10** :$ `some command` Some `code` *comment*

...至:

| **10** :$    
```console
some command
```

Some `code` *comment*

但是,我需要 Some code *comment*| **10** :$

保持在同一条线上

我为什么要问

这可能是 awk 的工作。即使我理解 awk,必要的正则表达式也让我望而却步。

我可能会在最后的 sed 语句中使用文本占位符,然后 grep 手动更改 Optional code *comments*。但是,我宁愿向社区贡献一个问题,这也可以节省我的时间。

使用捕获组和反向引用:

$ cat ip.txt
| **10** :$ `some command` Some `code` *comment*

$ sed -E 's/(\*\* :$) `([^`]+)`(.*)/\n\n```console\n\n```/' ip.txt
| **10** :$ Some `code` *comment*

```console
some command
```

(regexp) 将捕获匹配的部分,您可以稍后使用 </code>、<code> 等调用。最左边的 ( 得到组号 1,下一个最左边的 ( 得到数字 2 等等。

使用 GNU awk for gensub():

$ awk '{[=10=]=gensub(/([^`]*)`([^`]*)` (.*)/,"\1\3\n\n```console\n\2\n```",1)} 1' file
| **34** :$ Optional `code` comment, *maybe* with <kbd>Ctrl</kbd> + <kbd>Z</kbd>

```console
one cli command here
```

或使用 GNU awk 匹配第三个参数():

$ awk 'match([=11=],/([^`]*)`([^`]*)` (.*)/,a){[=11=]=a[1] a[3] "\n\n```console\n" a[2] "\n```"} 1' file
| **34** :$ Optional `code` comment, *maybe* with <kbd>Ctrl</kbd> + <kbd>Z</kbd>

```console
one cli command here
```

或使用任何 awk:

$ awk 'match([=12=],/`[^`]*`/){[=12=]=substr([=12=],1,RSTART-1) substr([=12=],RSTART+RLENGTH+1) "\n\n```console\n" substr([=12=],RSTART+1,RLENGTH-2) "\n```"} 1' file
| **34** :$ Optional `code` comment, *maybe* with <kbd>Ctrl</kbd> + <kbd>Z</kbd>

```console
one cli command here
```