gpt4 book ai didi

string - 用于替换较大子字符串中匹配子字符串的 Bash 脚本

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

我正在尝试编写一个 bash 脚本来替换注释中的换行符和 *,但前提是该注释包含特定的子字符串。

// file.txt
/**
* Here is a multiline
* comment that contains substring
* rest of it
*/

/**
* Here is a multiline
* comment that does not contain subNOTstring
* rest of it
*/

我希望最终结果是:

// file.txt
/** Here is a multiline comment that contains substring rest of it */

/**
* Here is a multiline
* comment that does not contain subNOTstring
* rest of it
*/

我有一个匹配多行注释的正则表达式:\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n] )))*\*\/ 但无法弄清楚第二部分,仅与子字符串匹配,然后将所有 /n * 替换为

所以要确保我的问题表述正确

  1. 匹配文件中的子字符串。即评论
  2. 确保匹配包括 substring
  3. 用另一个字符串替换第一个匹配项中的所有子字符串。即 n/*

最佳答案

如果 python 是您的选择,请尝试:

#!/usr/bin/python

import re # use regex module

with open('file.txt') as f: # open "file.txt" to read
str = f.read() # assign "str" to the lines of the file

for i in re.split(r'(/\*.*?\*/)', str, flags=re.DOTALL): # split the file on the comment including the comment in the result
if re.match(r'/\*.*substring', i, flags=re.DOTALL): # if the comment includes the keyword "substring"
i = re.sub(r'\n \* |\n (?=\*/)', ' ', i) # then replace the newline and the asterisk with a whitespace
print(i, end='') # print the element without adding newline
  • re.split(r'(/\*.*?\*/)', str, flags=re.DOTALL) 在评论中拆分“str”包括拆分列表中的评论。
  • flags=re.DOTALL 选项使点与换行符匹配。
  • for i in .. 语法循环遍历列表,将“i”分配给每个元素。
  • re.match(r'/\*.*substring', i, flags=re.DOTALL) 匹配元素这是包含关键字“substring”的注释。
  • re.sub(r'\n\* |\n (?=\*/)', ' ', i) 替换换行符后跟下一行中的“*”有一个空格。
  • \n (?=\*/) 是一个积极的前瞻,它匹配后面的换行符经过 ” */”。它将匹配注释 block 的最后一行离开"*/"原样。

[编辑]
如果你想在 bash 中嵌入 python 脚本,请尝试:

#!/bin/bash

infile="file.txt" # modify according to your actual filename
tmpfile=$(mktemp /tmp/temp.XXXXXX) # temporary file to output

# start of python script
python3 -c "
import re, sys

filename = sys.argv[1]
with open(filename) as f:
str = f.read()

for i in re.split(r'(/\*.*?\*/)', str, flags=re.DOTALL):
if re.match(r'/\*.*substring', i, flags=re.DOTALL):
i = re.sub(r'\n \* |\n (?=\*/)', ' ', i)
print(i, end='')
" "$infile" > "$tmpfile"
# end of python script

mv -f -- "$infile" "$infile".bak # backup the original file
mv -f -- "$tmpfile" "$infile" # replace the input file with the output

关于string - 用于替换较大子字符串中匹配子字符串的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73367150/

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