输入文件示例:
LINE1 LINE1 M) W1 W2 W3}N) REST
LINE2 LINE2 SOME OTHER WORDS
LINE3 LINE3 LINE3 M) Z1 Z2 Z3 Z4}N) REST
在模式M)和N)之间的匹配线中我需要替换所有空格但第一个空格,预期输出为:
LINE1 LINE1 M) W1W2W3}N) REST
LINE2 LINE2 SOME OTHER WORDS
LINE3 LINE3 LINE3 M) Z1Z2Z3Z4}N) REST
答案 0 :(得分:1)
GNU awk
解决方案:
awk 'match($0, /(M\) )(.+N\))/, a){
gsub(/[[:space:]]+/, "", a[2]);
sub(/M\) .+N\)/, a[1] a[2])
}1' file
输出:
LINE1 LINE1 M) W1W2W3}N) REST
LINE2 LINE2 SOME OTHER WORDS
LINE3 LINE3 LINE3 M) Z1Z2Z3Z4}N) REST
答案 1 :(得分:0)
关注awk
可能对您有帮助。
awk 'match($0,/M) .*N)/){val=substr($0,RSTART,RLENGTH);gsub(/ +/,"",val);sub("M)","M) ",val);print substr($0,1,RSTART-1) val substr($0,RSTART+RLENGTH+1);next} 1' Input_file
现在也添加非单线形式的解决方案。
awk '
match($0,/M) .*N)/){
val=substr($0,RSTART,RLENGTH);
gsub(/ +/,"",val);
sub("M)","M) ",val);
print substr($0,1,RSTART-1) val substr($0,RSTART+RLENGTH+1);
next}
1
' Input_file
输出如下。
LINE1 LINE1 M) W1W2W3}N)REST
LINE2 LINE2 SOME OTHER WORDS
LINE3 LINE3 LINE3 M) Z1Z2Z3Z4}N)REST
答案 2 :(得分:0)
你可以尝试这个sed:
sed -E ':A;s/(.*M\) )([^ ]*)( )(.*N\).*)/\1\2\4/;tA' infile