有如下的文本:
abcd 1234 fds
2011 550
1023 832er 1231
要求處理后如下所示:
abcd 1234 fds
2011 550
total1:1023 total2:832er 12end
判斷如果是文本最后一行則在第一列前面加total1:,第二列加total2:, 第三列后面減掉后面兩個字符并加end。
分別用sed與awk來實現(xiàn)。
sed:
復(fù)制代碼 代碼如下:
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:
復(fù)制代碼 代碼如下:
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}}'