如何使用Sed或awk使用递增的字母数字值来递归替换相同的值,并使用递增的字母数字值再次递归内部脚本脚本。它应该发生到第n个值到文件结尾
---输入文件如下----
<first line has same value as testname="tran cont" enabled="true">
<inner first line has url testname="/" enabled="true">
<inner second line has url testname="/test/dui/views?" enabled="true">
<first line has same value as testname="tran cont" enabled="true">
<inner first line has url testname="/test/TeDi/perf" enabled="true">
<inner second line has url testname="/Dest/Content/surf" enabled="true">
<inner third line has url testname="/Cest/dui/duff" enabled="true">
<first line has same value as testname="tran cont" enabled="true">
<inner first line has url testname="/test/dui/complete" enabled="true">
<inner second line has url testname="/test/dui/one" enabled="true">
<inner third line has url testname="/test/dui/two" enabled="true">
---输出要求如下----
<first line has same value as testname="A01" enabled="true">
<inner first line has url testname="A01_01" enabled="true">
<inner second line has url testname="A01_02_views?" enabled="true">
<first line has same value as testname="A02" enabled="true">
<inner first line has url testname="A02_01_perf" enabled="true">
<inner second line has url testname="A02_02_surf" enabled="true">
<inner third line has url testname="A02_03_duff" enabled="true">
<first line has same value as testname="A03" enabled="true">
<inner first line has url testname="A03_01_complete" enabled="true">
<inner second line has url testname="A03_02_one" enabled="true">
<inner third line has url testname="A03_03_two" enabled="true">
答案 0 :(得分:2)
以下是一些让你前进的地方:
awk -F\" '/^<first/ {a++;b=0} {n=split($2,s,"/");q=s[n];$2="A0"a ($0~/<inner/?"_0"++b"_"q:"")}1' OFS=\" file
<first line has same value as testname="A01" enabled="true">
<inner first line has url testname="A01_01_" enabled="true">
<inner second line has url testname="A01_02_views?" enabled="true">
<first line has same value as testname="A02" enabled="true">
<inner first line has url testname="A02_01_perf" enabled="true">
<inner second line has url testname="A02_02_surf" enabled="true">
<inner third line has url testname="A02_03_duff" enabled="true">
<first line has same value as testname="A03" enabled="true">
<inner first line has url testname="A03_01_complete" enabled="true">
<inner second line has url testname="A03_02_one" enabled="true">
<inner third line has url testname="A03_03_two" enabled="true">
工作原理:
awk -F\" ' # Set field separator to "
/^<first/ { # If record starts with <first then do:
a++ # Increment variable a
b=0} # Set b to 0
{ # For all run do:
n=split($2,s,"/") # Split data in field 2, to array s slitted by /. Sen variable n to number of data in array s
q=s[n] # Set variable q to last element in array s
$2="A0"a ($0~/<inner/?"_0"++b"_"q:"") # Set field 2 to: "A0" + value of a + ( if $0 equal "inner" to "_0" b (auto increment) "_" q, else "")
}
1 # Print the line
' OFS=\" file # Set Output Field Separator to " and read the file