在我的文件AppMacros.h
中,我有一行#define TARGET_DEVICE XXX
。 XXX
將在以後更改,所以我想找到以#define TARGET_DEVICE
字符串開頭的行,並將其替換爲特定的字符串,如#define TARGET_DEVICE YYY
。查找以特定字符串開頭的行並將其替換爲新行
任何人都知道如何使它在Groovy?
在我的文件AppMacros.h
中,我有一行#define TARGET_DEVICE XXX
。 XXX
將在以後更改,所以我想找到以#define TARGET_DEVICE
字符串開頭的行,並將其替換爲特定的字符串,如#define TARGET_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 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
}
NB:這個作品也非常大的文件導致過程行的文件行。使用的正則表達式放寬了空間約束(如果一行有多個空格或製表符,則它與該行相匹配)。
沒有我的運氣還是蛋白石答案?不同的方法(正則表達式,包含),但兩者都可以工作 –
對不起,延遲迴復,我的Macbook出現問題。我對你們兩個都沒有好運,我最終用這種方式。我寫了一個python腳本併成功運行它。非常感謝幫助我。 –
沒問題,很高興知道你已經解決了。祝你有美好的一天! –