有如下的文本:
abcd 1234 fds
2011 550
1023 832er 1231
要求处理后如下所示:
abcd 1234 fds
2011 550
total1:1023 total2:832er 12end
判断如果是文本最后一行则在第一列前面加total1:,第二列加total2:, 第三列后面减掉后面两个字符并加end。
分别用sed与awk来实现。
sed:
代码如下:
echo 'abcd 1234 fds
2011 550
1023 832er 1231' |sed -r '$s/([^ ]*)( )([^ ]*)( )(..).*$/total1:/1/2total:/3/4/5end/'
abcd 1234 fds
2011 550
total1:1023 total:832er 12end
awk:
代码如下:
awk 'NR>1{print a}{a=$0}END{$1="total1:"$1;$2="total2:"$2;print gensub(/..$/,"end",$0)}' file
awk 'BEGIN{getline a}{print a;a=$0}END{$1="total1:"$1;$2="total2:"$2;$3=gensub(/..$/,"end",1,$3);print}'
awk '{if(!getline line){print "total1:"$1" total2:"$2" "gensub(/..$/,"end",1,$3)}else{print line?$0 RS line:$0}}'
新闻热点
疑难解答