使用 Bash 将字符串添加到正则表达式匹配中

Prepend a String to a Regex Match Using Bash

我有一个文件,在某些行上有一个特定的字符串,这些字符串采用 [Name](./path_to_name_directory)[Name](./path_to_name_directory/notes.md) 的形式,每行都有一些不重要的列表项。对于 没有 在括号内的文件路径末尾具有 notes.md 的行,Name 被添加到该行的前面。

为了尝试解决这个问题,我最初有以下命令

sed 's/\[(.*)\]\(\.\/.*\/(?!notes\.md)/&/g' ./file.md

但我最终发现 sed 不支持先行或后行,因此我转而使用 perl 来尝试完成相同的任务。我以为这会像做一样简单

perl -pe 's/\[(.*)\]\(\.\/.*\/(?!notes\.md)/&/g'

但它没有用,我不完全确定从这里到哪里去。

编辑 1:

示例输入文件:

- [Name 1](./path_to_name_1)
  - Unimportant list item.
- [Name 2](./path_to_name_2/notes.md)
  - Unimportant list item.

示例输出文件:

- Name 1 [Name 1](./path_to_name_1)
  - Unimportant list item.
- [Name 2](./path_to_name_2/notes.md)
  - Unimportant list item.

使用您展示的示例,请尝试以下操作。

awk '
!/notes\.md\)$/ && match([=10=],/\[Name [0-9]+/){
  = OFS substr([=10=],RSTART+1,RLENGTH-1)
}
1
' Input_file

说明: 为以上添加详细说明。这仅用于解释目的。

awk '
##Starting awk program from here.
!/notes\.md\)$/ && match([=11=],/\[Name [0-9]+/){
##Checking condition if current does not end with notes.md) then match [Name digits in current line.
  = OFS substr([=11=],RSTART+1,RLENGTH-1)
##Re-create 1st field which has current  OFS and sub string of matched regex value.
}
1
##This will print current edited/non-edited line here.
' Input_file ##Mentioning Input_file name here.

我使用 @ 想出的一个选项 RavinderSingh13的回答this相关的回答如下

sed -E '/.*notes\.md.*/!s/\[(.*)\]/&/g'

/.*notes\.md.*/! 告诉 sed 如果字符串匹配正则表达式则不匹配。换句话说,sed 将只匹配与地址规范不匹配的行(参见 GNU Sed 手册 section 4.1 的代码块 #5)。

s/\[(.*)\]/&/g 告诉 sed 捕获组方括号的内部字符串并将其添加到整个匹配项之前;完成位置放置的正则表达式部分是 &,其中 </code> 是捕获组,<code>& 引用字符串的整个匹配部分。)

使用awk,您可以将FS设置为[][]|/|)。这样就可以得到</code>和<code>的内容,把条件放

awk -v FS='[][]|/|)' ' ~ /^Name [[:digit:]]/ &&  !~ /notes.md/ {sub(/^. /, "&"" " , [=10=])} 1' file
- Name 1 [Name 1](./path_to_name_1)
  - Unimportant list item.
- [Name 2](./path_to_name_2/notes.md)
  - Unimportant list item.