Groovy 查找以特定字符串开头的行并将其替换为新行

Groovy 查找以特定字符串开头的行并将其替换为新行,groovy,Groovy,在我的文件AppMacros.h中,我有一行#define TARGET_DEVICE XXXXXX稍后将更改,因此我想找到以\define TARGET\u DEVICE字符串开头的行,并将其替换为特定字符串,例如\define TARGET\u DEVICE YYY 有人知道如何用Groovy制作吗 这里只是一个示例-不知道您是否需要更高级的: def txt = ''' #define TARGET_DEVICE XXX lol #define TARGET_DEVICE XXX olo

在我的文件
AppMacros.h
中,我有一行
#define TARGET_DEVICE XXX
XXX
稍后将更改,因此我想找到以
\define TARGET\u DEVICE
字符串开头的行,并将其替换为特定字符串,例如
\define TARGET\u DEVICE YYY


有人知道如何用Groovy制作吗

这里只是一个示例-不知道您是否需要更高级的:

def txt = '''
#define TARGET_DEVICE XXX
lol
#define TARGET_DEVICE XXX
olo
#define TARGET_DEVICE XXX
'''

def replaced = txt.split('\n').collect { l ->
    def targetLine = l.toLowerCase().startsWith('#define target_device')
    targetLine ? '#define TARGET_DEVICE YYY' : l
}.join('\n')

println replaced

我假设您从命令行传递文件名(如果知道的话,它可以作为
sed-I~
),代码创建一个输出文件(名称相同,但后缀为
~
):

def模式=/^\s*(#定义\s+目标\u设备)\s+*/
def ls=System.getProperty(“line.separator”)
def newDevice=“XXX”
File fin=新文件(args[0]);
File fout=新文件(“${fin.name}~”)
if(fin.exists()&&!fin.isDirectory())
{
fin.eachLine{line->
line=line.replaceAll(模式){
重新匹配,前缀->
“${prefix}${newDevice}”
}
fout.append(“${line}${ls}”)
//或打印行

//或者LinesAccumerator没有我的答案或蛋白石答案?不同的方法(regex,contains)但是这两个工作都很抱歉,我的macbook出现了问题。我和你的macbook都不走运,我最终使用了这种方式。我编写了一个python脚本并成功运行了它。非常感谢你对我的帮助。没问题,很高兴知道你已经解决了。祝你愉快!
def pattern    = /^\s*(#define\s+TARGET_DEVICE)\s+.*/
def ls         =  System.getProperty("line.separator")
def newDevice  =  "XXX"
File fin       =  new File(args[0]);
File fout      =  new File("${fin.name}~")

if( fin.exists() && !fin.isDirectory() )
{
  fin.eachLine { line ->
      line = line.replaceAll(pattern) {
        entireMatch, prefix ->
          "${prefix} ${newDevice}"
      }
      fout.append("${line}${ls}")
      //or println line
      //or linesAccumulator << line
  }
} else {
  println "File ${args[0]} not exists or is a directory"
  System.exit 5
}