這裏是做
$ cat f.awk
function init() {
tag = "version.of.artifact"
b = "<" tag ">"
e = "</" tag ">"
lb = length(b)
le = length(e)
}
function upd(old) {
return "String"
}
function ss(s, a, b) { # substring of `s' from `a' to `b' excluding `b'
return substr(s, a, b-a)
}
function repl(s, ie, prefix, old, new, ans) {
while (ib = index(s, b)) {
ie = index(s, e)
if (!ie) {
print "ERROR: cannot find a closing tag" | "cat 1>&2"; exit 1
}
prefix = ss(s, 1, ib) # befor the tag
old = ss(s, ib + lb, ie) # old value of this tag
new = upd(old)
ans = ans prefix b new e
s = substr(s, ie + le) # after the tag
}
ans = ans s
return ans
}
BEGIN {
init()
}
{
print repl($0)
}
示例一個簡單的方法:
$ cat file.dat
text1
ab<version.of.artifact>1.2.3</version.of.artifact>cd<version.of.artifact>{1.2.3}</version.of.artifact>ef
<version.of.artifact>1.2.3</version.of.artifact>
text2
用法:
awk -f f.awk file.dat
輸出:
text1
ab<version.of.artifact>String</version.of.artifact>cd<version.of.artifact>String</version.of.artifact>ef
<version.of.artifact>String</version.of.artifact>
text2
所以,你知道,你可以捕捉一些文字與'\(... \)'然後引用它以後使用'\ 1'但無法弄清楚如何捕獲'。*'並在以後參考它?只要想一想,你現有的腳本在輸入行的每個部分都在做什麼 - 答案就在那裏。 –