【问题标题】:Change special inline code styling to block code styling in Markdown在 Markdown 中更改特殊的内联代码样式以阻止代码样式
【发布时间】:2021-08-24 05:17:53
【问题描述】:

我在 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*。但是,我更愿意为社区贡献一个问题,这也可以节省我的时间。

【问题讨论】:

    标签: github awk sed markdown


    【解决方案1】:

    使用捕获组和反向引用:

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

    (regexp) 将捕获匹配的部分,稍后您可以使用\1\2 等调用。最左边的( 获得组号1,最左边的( 获得编号2等等。

    【讨论】:

    • 这是一个插入代码,无需更改。恕我直言,这是“正确”的方式。 awk 可能是一个大锤,但awk 解决方案仍然受欢迎。
    • 我不会使用awk 来解决这个问题,因为我看不到操作字段的简单方法(特别是因为在要捕获的代码之后使用反引号)。如果您想使用替换功能,则需要 gawk 进行反向引用(与 sed 相比,语法更冗长)并且非 gawk 解决方案的解决方法将是乏味的。另见When to use grep, less, awk, sed
    • awk 不关心反引号。
    • @EdMorton 我的意思是在字段操作方面,如果一行中只有两个反引号,很容易知道有多少字段
    【解决方案2】:

    使用 GNU awk 进行 gensub():

    $ awk '{$0=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($0,/([^`]*)`([^`]*)` (.*)/,a){$0=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($0,/`[^`]*`/){$0=substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH+1) "\n\n```console\n" substr($0,RSTART+1,RLENGTH-2) "\n```"} 1' file
    | **34** :$ Optional `code` comment, *maybe* with <kbd>Ctrl</kbd> + <kbd>Z</kbd>
    
    ```console
    one cli command here
    ```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 2015-03-15
      • 2019-01-12
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多