gpt4 book ai didi

regex - 使用 Bash 将字符串添加到正则表达式匹配前面

转载 作者:行者123 更新时间:2023-12-02 18:49:51 25 4
gpt4 key购买 nike

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

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

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

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

perl -pe 's/\[(.*)\]\(\.\/.*\/(?!notes\.md)/\1&/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($0,/\[Name [0-9]+/){
$1=$1 OFS substr($0,RSTART+1,RLENGTH-1)
}
1
' Input_file

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

awk '
##Starting awk program from here.
!/notes\.md\)$/ && match($0,/\[Name [0-9]+/){
##Checking condition if current does not end with notes.md) then match [Name digits in current line.
$1=$1 OFS substr($0,RSTART+1,RLENGTH-1)
##Re-create 1st field which has current $1 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.

关于regex - 使用 Bash 将字符串添加到正则表达式匹配前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66938318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com