我有以下字符串:
signal[i]
signal[bg]
output [10:0]
input [i:1]
我想要的是替换方括号之间的字母(例如通过下划线)并保留表示表声明的其他字符串:
signal[_]
signal[__]
output [10:0]
input [i:1]
感谢
答案 0 :(得分:1)
替代 gawk 解决方案:
awk -F'\\[|\\]' '$2!~/^[0-9]+:[0-9]$/{ gsub(/./,"_",$2); $2="["$2"]" }1' OFS= file
输出:
signal[_]
signal[__]
output [10:0]
-F'\\[|\\]'
- 将[
和]
视为字段分隔符
$2!~/^[0-9]+:[0-9]$/
- 如果第二个字段不代表表格声明
gsub(/./,"_",$2)
- 用_
答案 1 :(得分:0)
尝试:
awk '{gsub(/\[[a-zA-Z]+\]/,"[_]")} 1' Input_file
全局替换(括号)字母直到最长匹配,然后用[_]代替。提及1将打印行(编辑或不编辑)。
编辑:上面会用一个_替换所有字母,所以要获得尽可能多的下划线,以下可能会有所帮助。
awk '{match($0,/\[[a-zA-Z]+\]/);VAL=substr($0,RSTART+1,RLENGTH-2);if(VAL){len=length(VAL);;while(i<len){q=q?q"_":"_";i++}};gsub(/\[[a-zA-Z]+\]/,"["q"]")}1' Input_file
或强>
awk '{
match($0,/\[[a-zA-Z]+\]/);
VAL=substr($0,RSTART+1,RLENGTH-2);
if(VAL){
len=length(VAL);
while(i<len){
q=q?q"_":"_";
i++
}
};
gsub(/\[[a-zA-Z]+\]/,"["q"]")
}
1
' Input_file
很快会添加解释。
EDIT2:以下是OP和用户的解释目的。
awk '{
match($0,/\[[a-zA-Z]+\]/); #### using match awk's built-in utility to match the [alphabets] as per OP's requirement.
VAL=substr($0,RSTART+1,RLENGTH-2); #### Creating a variable named VAL which has substr($0,RSTART+1,RLENGTH-2); which will have substring value, whose starting point is RSTART+1 and ending point is RLENGTH-2.
RSTART and RLENGTH are the variables out of the box which will be having values only when awk finds any match while using match.
if(VAL){ #### Checking if value of VAL variable is NOT NULL. Then perform following actions.
len=length(VAL); #### creating a variable named len which will have length of variable VAL in it.
while(i<len){ #### Starting a while loop which will run till the value of VAL from i(null value).
q=q?q"_":"_"; #### creating a variable named q whose value will be concatenated it itself with "_".
i++ #### incrementing the value of variable i with 1 each time.
}
};
gsub(/\[[a-zA-Z]+\]/,"["q"]") #### Now globally substituting the value of [ alphabets ] with [ value of q(which have all underscores in it) then ].
}
1 #### Mentioning 1 will print (edited or non-edited) lines here.
' Input_file #### Mentioning the Input_file here.
答案 2 :(得分:0)
这可能适合你(GNU sed);
sed ':a;s/\(\[_*\)[[:alpha:]]\([[:alpha:]]*\]\)/\1_\2/;ta' file
使用任意数量的_
和至少一个字母字符匹配开始和结束方括号,并用下划线替换所述字符并重复。
答案 3 :(得分:-1)
awk '{sub(/\[i\]/,"[_]")sub(/\[bg\]/,"[__]")}1' file
signal[_]
signal[__]
output [10:0]
input [i:1]
解释如下:由于括号是特殊字符,因此必须将其转义为字面处理,然后才能轻松使用sub。