CLI方法来替换regex捕获组中的空白



我有一些markdown文件,URL中有空格。我想用连字符替换URL中的空白。我不确定sed是否可能做到这一点。

例如:

[the name of the link](www.example.com/a badly named thing)

应该成为

[the name of the link[(www.example.com/a-badly-named-thing)

我知道我可以用下面的表达式捕获坏的url,但我怎么能用它做点什么呢?

s/[.*](/[/1/])/<do something to group 1>/g

您可以使用

sed -e ':a' -e 's/([[^][]*]([^()[:space:]]*)[[:space:]]{1,}([^()]*))/1-2/' -e 'ta' file > newfile

请参阅在线演示。

详细信息

  • :a-设置标签
  • ([[^][]*]([^()[:space:]]*)[[:space:]]{1,}([^()]*))——POSIX BRE模式匹配
    • ([[^][]*]([^()[:space:]]*)-第1组(1(:
      • [[^][]*]-一个[,然后是除][之外的零个或多个字符,然后是一个]
      • (-一个(字符
      • [^()[:space:]]*-除()和空白之外的零个或多个字符
    • [[:space:]]{1,}-一个或多个空白字符
    • ([^()]*))-第2组(2(:
      • [^()]*-除()之外的零个或多个字符
      • )-)字符
  • 1-2替换将匹配项替换为组1值+-+组2值
  • ta表示,如果替换成功,则引擎跳回到标签位置

使用GNUsed

$ sed -E ':a;s/(([^)]*) /(1-/;ta' input_file
[the name of the link](www.example.com/a-badly-named-thing)

Perl,但它相当粗糙:

perl -pe 's{ [.+?] ( K [^)]+ }{ $url = $&; $url =~ tr/ /-/; $url }xeg'

它匹配括号中的链接名称,然后是url部分的左括号,然后忘记了这些内容,然后匹配一系列非右括号。然后,匹配的文本被子脚本的结果所取代,该子脚本将空格更改为连字符

最新更新