- 论坛徽章:
- 93
|
括号和你的结果有此许不同,你检查检查,另外从简考虑,使用 /([a-z]+\([^()^]+\))\^([0-9])/ 的正则,所以暂不支持a(a(i))^2这样的嵌套格式,只支持 a(i)^2 的单层格式,如果有需要你再改进这个正则就行了:- [seesea2517@UC ~]# awk -f a.awk a.txt
- 原始:5*a(i)*a(j)*(a(k1)+3*a(k2))
- 替换:5*tensor(tensor(a(i),a(j)),(a(k1)+3*a(k2)))
- -------------
- 原始:a(i)^2*a(j)^2
- 替换:tensor(p_tensor(2,a(i)),p_tensor(2,a(j)))
- -------------
- 原始:3*a(3)^2+6*a(1)^2*(5*a(2)^2-2*a(4))+6*a(2)*a(4)+6*a(1)*(-4*a(2)*a(3)+a(5))
- 替换:3*p_tensor(2,a(3))+6*tensor(p_tensor(2,a(1)),(5*p_tensor(2,a(2))-2*a(4)))+
- 6*tensor(a(2),a(4))+6*tensor(a(1),(-4*tensor(a(2),a(3))+a(5)))
- -------------
- 原始:5*a(2)^2-2*a(4)
- 替换:5*p_tensor(2,a(2))-2*a(4)
- -------------
- [seesea2517@UC ~]# cat a.txt
- 5*a(i)*a(j)*(a(k1)+3*a(k2))
- a(i)^2*a(j)^2
- 3*a(3)^2+6*a(1)^2*(5*a(2)^2-2*a(4))+6*a(2)*a(4)+6*a(1)*(-4*a(2)*a(3)+a(5))
- 5*a(2)^2-2*a(4)
- [seesea2517@UC ~]# cat a.awk
- function tensor(line, _ARGEND_, ar, len, i, str, flag, ar_tokens, count, result,
- temp)
- {
- count = 0
- str = ""
- flag = 0
- i = 1
- len = split(line, ar, "")
- if (ar[1] == "(")
- {
- if (ar[len] != ")")
- {
- print "括号不匹配。"
- exit
- }
- ++i
- --len
- }
- for (; i <= len; ++i)
- {
- if (ar[i] == "(")
- flag++
- if (ar[i] == ")")
- flag--
- if (flag < 0)
- {
- print "括号不匹配。"
- exit
- }
- if (flag == 0 && (ar[i] ~ /[+*/]/ || (ar[i] == "-" && ar[i-1] ~ /[0-9)]/
- )))
- {
- ar_tokens[count++] = ar[i]
- str = ""
- continue
- }
- str = str""ar[i]
- if (i == len || (ar[i+1] ~ /[-+*/]/ && flag == 0))
- {
- if (str ~ /^\(/)
- {
- ar_tokens[count++] = "("tensor(str)")"
- } else {
- ar_tokens[count++] = str
- }
- }
- }
- result = ""
- temp = ""
- for (i = 0; i < count; ++i)
- {
- if (temp == "")
- temp = ar_tokens[i]
- if (ar_tokens[i+1] == "*" && temp !~ /^[-0-9]+$|^$/)
- {
- temp = "tensor("temp","ar_tokens[i+2]")"
- i += 2
- if (i < count)
- {
- i--
- continue
- }
- }
- result = result""temp
- temp = ""
- }
- return result
- }
- BEGIN {
- FS=""
- }
- {
- print "原始:" $0
- print "替换:" gensub(/([a-z]+\([^()^]+\))\^([0-9])/, "p_tensor(\\2,\\1)", "g", tensor($0))
- print "-------------"
- }
复制代码 |
|